简体   繁体   中英

Difference Between Timeit and Time in Python

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 ?

timeit will use the best available timing function on your system. See the docs on timeit.default_timer .

Also, timeit turns off the garbage collector .

Also, I believe you're using timeit wrong. You should be passing a string as per the last example in the documentation:

print timeit("pE1test2()","from __main__ import PE1test2",number=1)

And of course, another major difference is that timeit makes 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 (eg due to your system resources being hogged by some other program).

The purposes of the two modules are very different.

The time module provides low-level access to various time/date functions provided by the underlying system.

The timeit module is specifically for running performance tests.

As you point out, you can do simple timing using the functions in time, but there are a number of common pitfalls that people fall into when trying to do performance testing. timeit tries to mitigate those in order to get repeatable numbers that can be sensibly compared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM