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)?
Calculate Elapsed Time of a Function With time() Function of time Module in Python. The time() function gives us the current time in seconds. It returns a float value that contains the current time in seconds.
In the time
module, there are two timing functions: time
and clock
. 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 that clock
behaves different in separate systems:
clock
in your process).# ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point)
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:# linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point)
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()
and time.process_time()
. perf_counter
is being used by the timeit
module.
What you need is time()
function from time
module:
import time start = time.time() do_long_code() print "it took", time.time() - start, "seconds."
You can use timeit module for more options though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With