Sometimes, I like to time how long it takes parts of my code to run. I've checked a lot of online sites and have seen, at large, two main ways to do this. One is using time.time
and the other is using timeit.timeit
.
So, I wrote a very simple script to compare the two:
from timeit import timeit
from time import time
start = time()
for i in range(100): print('ABC')
print(time()-start, timeit("for i in range(100): print('ABC')", number=1))
Basically, it times how long it takes to print "ABC" 100 times in a for-loop. The number on the left is the results for time.time
and the number on the right is for timeit.timeit
:
# First run
0.0 0.012654680972022981
# Second run
0.031000137329101562 0.012747430190149865
# Another run
0.0 0.011262325239660349
# Another run
0.016000032424926758 0.012740166697164025
# Another run
0.016000032424926758 0.0440628627381413
As you can see, sometimes, time.time is faster and sometimes it's slower. Which is the better way (more accurate)?
timeit
is the better choice for timing chunks of code. It usestime.time()
(time.clock()
for Windows) and disables the garbage collector. Also, one trial isn't really enough. – Blender Jul 10 '13 at 19:34timeit
usestime.perf_counter
in Python 3.3+ – jfs Dec 11 '13 at 21:37