Explain Codes LogoExplain Codes Logo

Measuring elapsed time with the Time module

python
performance
best-practices
tools
Nikita BarsukovbyNikita Barsukov·Oct 4, 2024
TLDR

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:

import time start = time.time() # Start of our "race" # Add the code you want to time here elapsed = time.time() - start # Finish line! print(f"Elapsed: {elapsed} sec")

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.

import time import functools prof_data = {} def profile(func): @functools.wraps(func) def wrap(*args, **kwargs): # Ladies and gentlemen, on your marks, get set... start_time = time.perf_counter() result = func(*args, **kwargs) # ...BAM! The finish line! elapsed_time = time.perf_counter() - start_time # Logging the race time prof_data.setdefault(func.__name__, []).append(elapsed_time) return result return wrap

To initialise this professional stopwatch on any function, simply:

@profile def your_function(): # Your breathtaking code here pass

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():

from datetime import datetime start = datetime.now() # Exciting code section elapsed = datetime.now() - start print(f"Elapsed: {elapsed.total_seconds()} sec") # Because every sec counts!

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?

import time elapsed_seconds = time.time() - start formatted_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_seconds)) # Pretty time, isn't it? print(f"Formatted Time: {formatted_time}")

When timing challenges last longer than your favorite Netflix series, use the monotonic counters time.perf_counter() or time.monotonic().