I'm just trying to time a piece of code. The pseudocode looks like:
start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."
How does this look in Python?
More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
In the
time
module, there are two timing functions:time
andclock
.time
gives you "wall" time, if this is what you care about.However, the python docs say that
clock
should be used for benchmarking. Note thatclock
behaves different in separate systems:clock
in your process).clock
reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:Apart from all that, the timeit module has the
Timer
class that is supposed to use what's best for benchmarking from the available functionality.¹ unless threading gets in the way…
² Python ≥3.3: there are
time.perf_counter()
andtime.process_time()
.perf_counter
is being used by thetimeit
module.From midnight:
If you have many statements you want to time, you could use something like this:
Then your code could look like:
That way you don't need to type
t = time()
before each block and1000 * (time() - t)
after it, while still keeping control over formatting (though you could easily put that inTicket
too).It's a minimal gain, but I think it's kind of convenient.
Here's a solution that I started using recently:
You use it like this (You need at least Python 2.5):
When your code finishes, Timer automatically prints out the run time. Sweet! If I'm trying to quickly bench something in the Python Interpreter, this is the easiest way to go.
And here's a sample implementation of 'now' and 'format_delta', though feel free to use your preferred timing and formatting method.
Please let me know if you have a preferred formatting method, or if there's an easier way to do all of this!
What you need is
time()
function fromtime
module:You can use timeit module for more options though.
The time module in python gives you access to the clock() function, which returns time in seconds as a floating point.
Different systems will have different accuracy based on their internal clock setup (ticks per second) but it's generally at least under 20milliseconds, and in some cases better than a few microseconds.
-Adam