python - time.time vs. timeit.timeit -


sometimes, time how long takes parts of code run. i've checked lot of online sites , have seen, @ large, 2 main ways this. 1 using time.time , other using timeit.timeit.

so, wrote simple script compare two:

from timeit import timeit time import time start = time() in range(100): print('abc') print(time()-start, timeit("for in range(100): print('abc')", number=1)) 

basically, times how long takes print "abc" 100 times in for-loop. number on left results time.time , number on right timeit.timeit:

# first run 0.0 0.012654680972022981 # second run 0.031000137329101562 0.012747430190149865 # run 0.0 0.011262325239660349 # run 0.016000032424926758 0.012740166697164025 # run 0.016000032424926758 0.0440628627381413 

as can see, sometimes, time.time faster , it's slower. better way (more accurate)?

timeit more accurate, 3 reasons:

  • it repeats tests many times eliminate influence of other tasks on machine, such disk flushing , os scheduling.
  • it disables garbage collector prevent process skewing results scheduling collection run @ inopportune moment.
  • it picks accurate timer os, time.time or time.clock, see timeit.default_timer.

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -