0

I am trying to measure the performance of contains() function in python. I a doing that by using the time module of python.

Here is the code which looks like this:

from time import time

def contains(collection, target):
    return target in collection


def performance():

    n = 1024

    while n < 50000000:
        sorted = range(n)
        now  = time()

        # code whose performance
        #
        # is to be evaluated
        contains(sorted, -1)

        done = time()

        print(n, (done-now)*1000)
        n *= 2

performance()

The problem that I have is that I always observe 0 time difference even though I increase the decimal places. I am missing some flag from time() module. Also I am using python 3.7. I should say that my machine is not that fast to have 0 time passed between the lines.

Here is the output:

1024 0.0
2048 0.0
4096 0.0
8192 0.0
16384 0.0
32768 0.0
65536 0.0
131072 0.0
262144 0.0
524288 0.0
1048576 0.0
2097152 0.0
4194304 0.0
8388608 0.0
16777216 0.0
33554432 0.0

Process finished with exit code 0
Erindy
  • 135
  • 9

1 Answers1

1

The problem that I have is that I always observe 0 time difference even though I increase the decimal places.

This is because the operation you are timing is effectively instantaneous.

range() returns a range object, not a list. These objects can be iterated over like a list, but they use optimized implementations of operations like in and indexing. In this case, the implementation of in merely needs to check that the number is between the minimum and maximum value of the range -- the speed of this operation does not depend on the size of the range.

If you want to test the performance of your function with large lists, you will need to cast the range to a list, e.g.

sorted_numbers = list(range(n))

(You should avoid using the name sorted for variables, because there is a builtin function with that name.)

duskwuff -inactive-
  • 171,163
  • 27
  • 219
  • 269