What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
import timeit start = timeit.timeit() print("hello") end = timeit.timeit() print(end - start)
In order to calculate the time elapsed in executing a code, the time module can be used. Save the timestamp at the beginning of the code start using time() . Save the timestamp at the end of the code end . Find the difference between the end and start, which gives the execution time.
In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.
If you just want to measure the elapsed wall-clock time between two points, you could use time.time()
:
import time start = time.time() print("hello") end = time.time() print(end - start)
This gives the execution time in seconds.
Another option since 3.3 might be to use perf_counter
or process_time
, depending on your requirements. Before 3.3 it was recommended to use time.clock
(thanks Amber). However, it is currently deprecated:
On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function
QueryPerformanceCounter()
. The resolution is typically better than one microsecond.Deprecated since version 3.3: The behaviour of this function depends on the platform: use
perf_counter()
orprocess_time()
instead, depending on your requirements, to have a well defined behaviour.
Use timeit.default_timer
instead of timeit.timeit
. The former provides the best clock available on your platform and version of Python automatically:
from timeit import default_timer as timer start = timer() # ... end = timer() print(end - start) # Time in seconds, e.g. 5.38091952400282
timeit.default_timer is assigned to time.time() or time.clock() depending on OS. On Python 3.3+ default_timer is time.perf_counter() on all platforms. See Python - time.clock() vs. time.time() - accuracy?
See also:
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