Timing python function

461 views Asked by At

(Python 2.7.8, Windows)

there is so many questions already about this particular subject, but I cannot seem to get any of them working.

So, what I'm trying to accomplish is timing how long a function takes to execute.

I have functions.py and main.py in following fashion:

#functions.py
def function(list):
    does something
    return list
...

#main.py
import functions
...stuff...
while:
    list = gets list from file
    functions.function(list) <--- this needs to get timed

Now I tried time.time() the start and end points first, but it's not accurate enough (difference tends to be 0.0), and after some googling it seems that this isn't the way to go anyway. Apparently what I should use(?) is timeit module. However I cannot understand how to get the function into it.

Any help?

3

There are 3 answers

1
oxymor0n On BEST ANSWER

As you mentioned, there's a Python module made for this very task, timeit. Its syntax, while a little idiosyncratic, is quite easy to understand:

timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)

stmt is the function call to be measured, in your case: functions.function(list)

setup is the code you need to create the context necessary for stmt to execute, in your case: import functions; list = gets list from file

number is how many time timeit would run stmt to find its average execution time. You might want to change the number, since calling your function a million times might take a while.

tl;dr:

timeit.timeit(stmt='functions.function(list)', setup='import functions; list = gets list from file', number=100)
5
Corey Goldberg On
start = timeit.default_timer()
my_function()
elapsed = timeit.default_timer() - start
3
Hackaholic On

you see this demo: time.time

>>> def check(n):
...     start = time.time()
...     for x in range(n):
...         pass     
...     stop = time.time()
...     return stop-start
... 
>>> check(1000)
0.0001239776611328125
>>> check(10000)
0.0012159347534179688
>>> check(100)
1.71661376953125e-05

the above function returns hum much time in sec taken by for for n loops.

so the algorithm is:

start = time.time()
# your stuff
stop = time.time()
time_taken = stop - start