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)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…