On this page
profile
Prev: pprint | Up: stdlib_module | Next: pstats
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — profile
Tags: #public #python3 #stdlib
Import
import profile
Overview
Pure-Python deterministic function profiler (profile.Profile, profile.run()), sharing the same API and .prof output format as the C-accelerated cProfile module. Reach for cProfile for everyday profiling; use profile only when you need to subclass Profile in Python or run in an environment where C extensions are unavailable.
Quick Start
import io
import profile
import pstats
pr = profile.Profile()
pr.enable()
total = sum(i * i for i in range(1000))
pr.disable()
buf = io.StringIO()
pstats.Stats(pr, stream=buf).sort_stats("tottime").print_stats(5)
assert "function calls" in buf.getvalue()
Implementation Walkthrough
1. Calibrating Pure-Python Overhead
Because profile is written in Python, it adds noticeable overhead to every function call. You can measure and set bias on a Profile instance using pr.calibrate(10000) to compensate for interpreter dispatch cost before recording timings.
Gotchas & Boundaries
- Much slower than cProfile:
profilecan slow down call-heavy code by 5×–10×; always default tocProfileunless you specifically need to subclass the profiler. - Analyze output with pstats: Both
profileandcProfilewrite compatible binary stats files readable bypstats.Stats. - Deterministic vs. sampling:
profileinstruments every Python call; for low-overhead production profiling, use a sampling profiler likepy-spyorscalene.
Common Functions
- profile.run() —
run(statement, filename=None, sort=-1)— Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this - profile.runctx() —
runctx(statement, globals, locals, filename=None, sort=-1)— Run statement under profiler, supplying your own globals and locals, optionally saving results in filename.
Classes & Objects
- profile.Profile — Profiler class. (Methods:
.calibrate(),.create_stats(),.dump_stats(),.fake_code(),.fake_frame(),.print_stats())
Linked from
Related notes
- tuts/python3/stdlib_module/pprint Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pstats Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/annotationlib Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/cProfile Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/doctest Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/profile/Profile Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/profile/run Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/profile/runctx Linked here; shared tags: #stdlib