When you need to speed up your code or understand where a bottleneck is, profiling is one of the most effective techniques.
The Python standard library provides a built-in profiler that traces the execution and timing for each function and allows you to spot the functions that are more expensive or that run too many times, consuming most of the execution time.
For this recipe, the following steps are to be performed:
- We can take any function we want to profile (which can even be the main entry point of the program):
import time def slowfunc(goslow=False): l = [] for i in range(100): l.append(i) if goslow: time.sleep(0.01) return l
- We can profile it using the
cProfile
module:
from cProfile import Profile profiler = Profile() profiler.runcall(slowfunc, True) profiler.print_stats()
202 function calls in 1.183 seconds
Ordered by: standard...