cProfile is Python’s built-in function-level CPU profiler. It records function-call counts and timing information with minimal setup, helping locate application hotspots before release. section 7.2.3
Listing 7.3 Python CPU profiling with cProfile
import cProfile
import pstats
profiler = cProfile.Profile() #A
profiler.enable()
# Your code here
process_request(request_data) #B
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative') #C
stats.print_stats(20) #DWrap the suspected operation with cProfile, collect pstats output, sort by cumulative time, and inspect the highest-cost functions. section 7.2.3
Read the results by separating local work from downstream work:
- tottime measures time spent inside a function, excluding calls it makes. section 7.2.3
- cumtime includes the function and everything in its call chain. section 7.2.3
- High cumtime with low tottime points deeper into the call chain; high tottime identifies work inside the function itself. section 7.2.3
Interpreting a slow request
If serialize_response reports 400 ms of cumtime but only 5 ms of tottime, inspect its callees rather than blaming serialization. A database function showing 310 ms of tottime is a stronger investigation target. section 7.2.3


