Measuring elapsed time with the Time module
Here is a quick way to measure the execution time of your code in Python with the time
module. Simply record the time at two points and subtract them to find the duration:
The above snippet records the time before and after your code block - giving you the elapsed time in seconds when executed.
Augmenting precision and accomplishing profiling
Although time.time()
serves its purpose, we sometimes need a stopwatch with better precision or more functionality. The time
module offers time.perf_counter()
, able to provide microsecond precision while maintaining monotonicity (regardless of system clock changes) - but it is adverse to long duration (100 days+).
Create a versatile decorator to profile multiple functions simultaneously. Decorators with functools.wraps
preserves the metadata of the original function.
To initialise this professional stopwatch on any function, simply:
Post the race, use print_prof_data()
to unveil the race statistics. Reset the statistics with clear_prof_data()
for a fresh set of measurements.
Identifying the right timer for the job
Depending on what your code is doing, different time
functions may come in handy. For CPU-bound tasks, gauging the CPU time using time.process_time()
is the way to go; your wait for I/O operations or delay simulation is time.sleep()
's forte.
Racing involves both Processor Time (the CPU's "race time") and Wall-Clock Time (the actual "race time" including the time taken for commercial breaks). Recognising their roles in the race is critical for successfully timing your code.
High-resolution timing while fighting the clock
For high-resolution timing in Python 3.7+, consider datetime.now()
:
For a more elegant presentation, convert elapsed time from seconds to a human-readable format using time.strftime()
and time.gmtime()
. Who says programmers can't be classy?
When timing challenges last longer than your favorite Netflix series, use the monotonic counters time.perf_counter()
or time.monotonic()
.
Was this article helpful?