Best way to time algorithms in Python

There are tons of ways to calculate elapsed time (in seconds) for Python code. But which is the best way?

So far, I find that the “timeit” method seems to give good results, and is easy to implement. Source: https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python

Use timeit.default_timer instead of timeit.timeit. The former provides the best clock available on your platform and version of Python automatically:

from timeit import default_timer as timer

start = timer()
# ...
end = timer()
print(end - start) # Time in seconds, e.g. 5.38091952400282

This is the answer by the user “jfs” on Stack Overflow.

Benefits of the above method include:

  • Using timeit will produce far more accurate results since it will automatically account for things like garbage collection and OS differences (comment by user “lkgarrison”)

Please comment below if you know other ways of measuring elapsed time on Python!

Other methods include:

  • time.clock()  (Deprecated as of Python 3.3)
  • time.time() (Is this a good method?)
  • time.perf_counter() for system-wide timing,
  • or time.process_time() for process-wide timing

 

Unknown's avatar

Author: mathtuition88

Math and Education Blog

3 thoughts on “Best way to time algorithms in Python”

Leave a reply to iamvistinginstructoreric Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.