Explain Codes LogoExplain Codes Logo

How do I get time of a Python program's execution?

python
performance
profiling
timers
Alex KataevbyAlex Kataev·Aug 22, 2024
TLDR

To measure the execution time of a script, use Python's built-in time module. You first capture the start time, execute your code, then capture the end time. The difference between start and end times is your execution time:

import time start = time.time() # Trust me I'm an engineer this is where your code goes duration = time.time() - start print(f"Executed in {duration:.4f} sec.")

This way you can get a crude estimation of how long your code takes to run.

Trying your hand at timing

If you need increased precision for your measurements, switch to time.perf_counter(). It provides a high-resolution timer which is more suitable for timing small sections of code. To present the time duration in a more user-friendly format, use the datetime.timedelta function:

import time from datetime import timedelta start = time.perf_counter() # Right here, this is where all the magic happens end = time.perf_counter() duration = timedelta(seconds=end-start) print(f'Execution Time: {duration}')

Quick and Dirty Command Line Timing

For those who love the terminal, whip up a quick execution time using time on the command line:

$ time python your-script.py

This would give you a rough idea of the execution time. Spice it up with -v(verbose mode) to get detailed juice on execution:

$ time -v python your-script.py

These would give you insights into memory usage, context switches, I/O stats, among other things.

Precision and Performance

Choose the right tool for the job

Depending on the specificity of your task, you'll need to select an appropriate timer:

  • time.time() for simple, non-critical timings
  • time.process_time() when you care about CPU time
  • time.perf_counter() for high-precision wall-clock measurements
  • time.monotonic() to avoid hiccups due to system clock updates

In-depth Code Profiling

For an in-depth understanding of where exactly your code is spending most of its time, you can go nuclear with Python's built-in cProfile module:

import cProfile cProfile.run('your_mystery_function()')

This will output a detailed performance report of your function, basically the blueprint of your code's runtime behavior.

System-Level Performance

To monitor system-level performance, memory usage and context switches, the secret might lie outside Python; more precisely, in Linux's /usr/bin/time:

/usr/bin/time -v python your-script-here.py

Verbose mode will provide insights into memory consumption and process scheduling, keys to the elusive land of optimized code.