Python pstats Module
Example
Profile a function inline and print the top rows (no file needed):
import cProfile, pstats
def work():
s = 0
for i in range(20000):
s += i*i
return s
pr = cProfile.Profile()
pr.enable()
work()
pr.disable()
pstats.Stats(pr).strip_dirs().sort_stats("time").print_stats(5)
Try it Yourself »
Definition and Usage
The pstats module reads and reports profiling data produced by profile
or cProfile
.
Use it to sort and print the most time-consuming functions, and to compare multiple runs.
Members
Member | Description |
---|---|
Stats | Main class for loading and analyzing profiling results. |
Stats.add() | Merge in data from another stats file or Stats object. |
Stats.print_callers() | Print callers for the profiled functions. |
Stats.print_callees() | Print callees for the profiled functions. |
Stats.print_stats() | Print a summary table (you can specify how many rows to show). |
Stats.sort_stats() | Sort by a key like time , cumulative , or calls . |
Stats.strip_dirs() | Remove leading path prefixes to shorten file names in output. |