Difference between time and time in Python
Is there a 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)
I'll use Project Euler 1 as an example (because it's very 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)
Output:
>>>
233168
0.0090000629425
233168
0.00513921300363
What is the main difference between timeit
and time
?
source to share
timeit
will use the best sync feature available on your system. See docs on timeit.default_timer
.
Also timeit
disables the garbage collector .
Also, I believe you are using it timeit
wrong. You have to pass the string according to the latest example in the documentation:
print timeit("pE1test2()","from __main__ import PE1test2",number=1)
And, of course, another significant difference is what timeit
makes it trivial in time to execute the function for thousands of iterations (this is the only time the result of synchronization makes sense). This diminishes the importance of one run that takes longer than others (for example, because your system resources are obfuscated by some other program).
source to share
The objectives of the two modules are very different.
The time module provides low-level access to the various time and date functions provided by the underlying system.
The timeit module is designed to run performance tests.
As you point out, you can make simple timing using functions over time, but there are a number of common mistakes people run into when trying to perform performance testing. timeit tries to soften them up to get duplicate numbers that can reasonably be compared.
source to share