Is there any significant difference between:
from time import time
start = time()
# some process
print time() - start
and:
from timeit import timeit
def my_funct():
# some process
print timeit(my_funct, number=1)
For an example, I’ll use Project Euler 1 (because it’s really easy to understand/solve)
def pE1test1(): # using time()
from time import time
start = time()
print sum([n for n in range(1, 1000) if n%3==0 or n%5==0])
print time() - start
def pE1test2(): # using timeit
print sum([n for n in range(1, 1000) if n%3==0 or n%5==0])
from timeit import timeit
pE1test1()
print timeit(pE1test2, number=1)
This outputs:
>>>
233168
0.0090000629425
233168
0.00513921300363
What is the major difference between timeit and time?
timeitwill use the best available timing function on your system. See the docs ontimeit.default_timer.Also,
timeitturns off the garbage collector.Also, I believe you’re using
timeitwrong. You should be passing a string as per the last example in the documentation:And of course, another major difference is that
timeitmakes it trivial to time the execution of the function for thousands of iterations (which is the only time a timing result is meaningful). This decreases the importance of a single run taking longer than the others (e.g. due to your system resources being hogged by some other program).