Skip to the content.

Performance Measurement

Wall Clock Time

import time

t0 = time.perf_counter()
# do something ...
wall_clock_time = time.perf_counter() - t0

time.perf_counter_ns() returns the value in nanoseconds.

CPU Time

import time

t0 = time.process_time()
# do something ...
cpu_time = time.process_time() - t0

time.process_time_ns() returns the value in nanoseconds.

timeit - Execution time of small code snippets

$ python -m timeit -n 10000 -r 5 -p '"-".join(str(n) for n in range(100))'
10000 loops, best of 5: 30.2 usec per loop

Options

cProfile / profile - Deterministic Profiling

python -m cProfile <x>.py

Profiling Modules

python -m cProfile -m <module>

Writes the profile results to a file

-o option:

python -m cProfile -o <result.pstats> <x>.py

Profiling Visualization

pipx install snakeviz
snakeviz <result.pstats>

References