I\'m new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.
In java, I would write:
python -m timeit -h
Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit
's default_timer()
:
>>> import timeit
>>> tic=timeit.default_timer()
>>> # Do Stuff
>>> toc=timeit.default_timer()
>>> toc - tic #elapsed time in seconds
This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.
ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.
For more precise/complex performance calculations, timeit
includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.
For Python 3.3 and later time.process_time() is very nice:
import time
t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t