Guy
Guy

Reputation: 115

python-measure function time

I am having a problem with measuring the time of a function.

My function is a "linear search":

def linear_search(obj, item,):
    for i in range(0, len(obj)):
        if obj[i] == item:
        return i
    return -1

And I made another function that measures the time 100 times and adds all the results to a list:

def measureTime(a):
    nl=[]
    import random
    import time
    for x in range(0,100): #calculating time
        start = time.time() 
        a   
        end =time.time()
        times=end-start
        nl.append(times)
    return nl

When I'm using measureTime(linear_search(list,random.choice(range(0,50)))), the function always returns [0.0].

What can cause this problem? Thanks.

Upvotes: 0

Views: 1145

Answers (2)

Skycc
Skycc

Reputation: 3555

you are actually passing the result of linear_search into function measureTime, you need to pass in the function and arguments instead for them to be execute inside measureTime function like @martijnn2008 answer

Or better wise you can consider using timeit module to to the job for you

from functools import partial
import timeit
def measureTime(n, f, *args):
    # return average runtime for n number of times
    # use a for loop with number=1 to get all individual n runtime
    return timeit.timeit(partial(f, *args), number=n)

# running within the module
measureTime(100, linear_search, list, random.choice(range(0,50)))

# if running interactively outside the module, use below, lets say your module name mymodule
mymodule.measureTime(100, mymodule.linear_search, mymodule.list, mymodule.random.choice(range(0,50)))

Upvotes: 1

martijnn2008
martijnn2008

Reputation: 3640

Take a look at the following example, don't know exactly what you are trying to achieve so I guessed it ;)

import random
import time

def measureTime(method, n, *args):
    start = time.time()
    for _ in xrange(n):
        method(*args)
    end = time.time()
    return (end - start) / n

def linear_search(lst, item):
    for i, o in enumerate(lst):
        if o == item:
            return i
    return -1

lst = [random.randint(0, 10**6) for _ in xrange(10**6)]
repetitions = 100
for _ in xrange(10):
    item = random.randint(0, 10**6)
    print 'average runtime =', 
    print measureTime(linear_search, repetitions, lst, item) * 1000, 'ms'

Upvotes: 0

Related Questions