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:
long timeBefore = System.currentTimeMillis();
doStuff();
long timeAfter = System.currentTimeMillis();
elapsed time = timeAfter - timeBefore;
I'm sure it's even easier in Python. Can anyone help?
If all you want is the time between two points in code (and it seems that's what you want) I have written
tic()
toc()
functions ala Matlab's implementation. The basic use case is:Super, incredibly easy to use, a sort of fire-and-forget kind of code. It's available on Github's Gist https://gist.github.com/tyleha/5174230
Equivalent in python would be:
If you are trying to find the best performing method then you should probably have a look at
timeit
.For Python 3.3 and later
time.process_time()
is very nice:Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use
timeit
'sdefault_timer()
: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.You can implement two
tic()
andtac()
functions, wheretic()
captures the time which it is called, andtac()
prints the time difference sincetic()
was called. Here is a short implementation:Now in your code you can use it as:
and it will, for example, output:
See also: