Profiling
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.
How to do it...
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()
- That will print the timing for the function and the slowest functions called by the profiled one:
202 function calls in 1.183 seconds
Ordered by: standard...