How do I get time of a Python program's execution?
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:
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:
Quick and Dirty Command Line Timing
For those who love the terminal, whip up a quick execution time using time
on the command line:
This would give you a rough idea of the execution time. Spice it up with -v
(verbose mode) to get detailed juice on execution:
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 timingstime.process_time()
when you care about CPU timetime.perf_counter()
for high-precision wall-clock measurementstime.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:
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
:
Verbose mode will provide insights into memory consumption and process scheduling, keys to the elusive land of optimized code.
Was this article helpful?