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
timemodule, there are two timing functions:timeandclock.timegives you ‘wall’ time, if this is what you care about.However, the python docs say that
clockshould be used for benchmarking. Note thatclockbehaves different in separate systems:clockin your process).clockreports 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
Timerclass 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_counteris being used by thetimeitmodule.