Performance Profiling with cProfile & pstats
Never optimize by guesswork. Standard library `cProfile` instruments function invocations using C-level hooks, while `pstats.Stats` sorts hotspots by internal execution time (`tottime`) or cumulative time (`cumtime`) ⏱️.
import cProfile
import io
import pstats
def intensive_task():
return sum(x * x for x in range(50_000))
profiler = cProfile.Profile()
profiler.enable()
intensive_task()
profiler.disable()
stream = io.StringIO()
stats = pstats.Stats(profiler, stream=stream).sort_stats("cumulative")
stats.print_stats(3)
print(f"Profiler stats generated! ⏱️")
# 116. Performance Profiling with cProfile & pstats Never optimize by guesswork. Standard library `cProfile` instruments function invocations using C-level hooks, while `pstats.Stats` sorts hotspots by internal execution time (`tottime`) or cumulative time (`cumtime`) ⏱️. ```python import cProfile import io import pstats def intensive_task(): return sum(x * x for x in range(50_000)) profiler = cProfile.Profile() profiler.enable() intensive_task() profiler.disable() stream = io.StringIO() stats = pstats.Stats(profiler, stream=stream).sort_stats("cumulative") stats.print_stats(3) print(f"Profiler stats generated! ⏱️") ``` For visual flamegraphs, save profiler stats via `profiler.dump_stats("profile.prof")` and load with tools like SnakeViz or py-spy to pinpoint exact bottleneck lines instantly 🏎️! --- ### Question What distinguishes `tottime` from `cumtime` in a `pstats` profile report? 🧠 - [ ] a. `tottime` measures time spent strictly in the function body; `cumtime` includes time inside all nested sub-function calls ⏱️ - [ ] b. `tottime` is CPU hardware cycles; `cumtime` is network socket wait time - [ ] c. `cumtime` only records garbage collection pauses - [ ] d. `tottime` is exclusive to asynchronous coroutines --- ### Challenge Profile `def work(): return [x for x in range(5000)]` with `cProfile.Profile()`. Print stats to `io.StringIO()`. Assert `'work'` in output and print `'PROFILE_SUCCESS'`. 🎯 <details> <summary>Solution</summary> ```python import cProfile, pstats, io def work(): return [x for x in range(5000)] pr = cProfile.Profile() pr.enable() work() pr.disable() s = io.StringIO() pstats.Stats(pr, stream=s).sort_stats('cumulative').print_stats() assert 'work' in s.getvalue() print('PROFILE_SUCCESS') ``` </details>