0
# Framework Integration
1
2
Built-in integration capabilities for popular Python frameworks and development environments including Jupyter notebooks, IPython magic commands, command-line usage, and decorator/context manager patterns for easy adoption.
3
4
## Capabilities
5
6
### Jupyter/IPython Integration
7
8
Magic commands for interactive profiling in Jupyter notebooks and IPython shells with support for cell-level and line-level profiling.
9
10
```python { .api }
11
def load_ipython_extension(ipython):
12
"""
13
Load pyinstrument IPython extension for magic commands.
14
15
Usage in IPython/Jupyter:
16
%load_ext pyinstrument
17
18
Args:
19
ipython: IPython instance to register magic commands with
20
"""
21
22
class PyinstrumentMagic:
23
"""
24
IPython magic commands for profiling code in interactive environments.
25
26
Available magics:
27
%pyinstrument - Profile a single line of code
28
%%pyinstrument - Profile an entire cell
29
"""
30
31
@line_cell_magic
32
def pyinstrument(self, line: str, cell: str | None = None):
33
"""
34
Profile code execution with various output options.
35
36
Line magic: %pyinstrument code_to_profile()
37
Cell magic: %%pyinstrument
38
code_to_profile()
39
more_code()
40
41
Options:
42
-p, --render-option: Renderer options (flag_name or option_name=option_value)
43
--show-regex: Regex matching file paths whose frames to always show
44
--show: Glob-style pattern matching file paths to show
45
--interval: Sampling interval in seconds (default: 0.001)
46
--show-all: Show all frames including root and internal IPython frames
47
--async_mode: Async handling mode (disabled, enabled, strict, default: disabled)
48
--height: Output height for HTML renderer (default: 400)
49
--timeline: Show timeline view (default: False)
50
"""
51
```
52
53
### Context Manager and Decorator
54
55
Convenient decorator and context manager interfaces for easy integration with existing code.
56
57
```python { .api }
58
class ProfileContext:
59
"""Context manager and decorator for profiling code blocks."""
60
61
def __init__(
62
self,
63
interval: float = 0.001,
64
async_mode: AsyncMode = "disabled",
65
use_timing_thread: bool | None = None,
66
renderer: Renderer | None = None,
67
target_description: str | None = None
68
):
69
"""
70
Initialize profiling context.
71
72
Args:
73
interval: Sampling interval in seconds
74
async_mode: Async handling mode
75
use_timing_thread: Use separate timing thread
76
renderer: Output renderer (defaults to ConsoleRenderer)
77
target_description: Description for profiling session
78
"""
79
80
def __call__(self, func: Callable | None = None, /, **kwargs):
81
"""
82
Use as decorator or create new context with updated options.
83
84
As decorator:
85
@profile
86
def my_function():
87
pass
88
89
With options:
90
@profile(interval=0.005, renderer=HTMLRenderer())
91
def my_function():
92
pass
93
"""
94
95
def __enter__(self):
96
"""Enter context manager and start profiling."""
97
98
def __exit__(self, exc_type, exc_value, traceback):
99
"""Exit context manager, stop profiling, and display results."""
100
101
def profile(**kwargs) -> ProfileContext:
102
"""
103
Create a profiling context manager or decorator.
104
105
Usage as context manager:
106
with profile():
107
code_to_profile()
108
109
Usage as decorator:
110
@profile
111
def function_to_profile():
112
pass
113
114
Args:
115
**kwargs: Configuration options passed to ProfileContext
116
117
Returns:
118
ProfileContext instance
119
"""
120
```
121
122
### Command Line Interface
123
124
Complete command-line interface for profiling Python scripts and modules.
125
126
```python { .api }
127
def main():
128
"""
129
Main entry point for pyinstrument command-line interface.
130
131
Usage:
132
pyinstrument script.py [args...]
133
python -m pyinstrument script.py [args...]
134
135
Options:
136
--interval: Sampling interval in seconds
137
--async-mode: Async handling mode
138
--renderer: Output format (text, html, json, speedscope)
139
--outfile: Output file path
140
--show-all: Show all frames including library code
141
--timeline: Show timeline view (HTML renderer)
142
--unicode: Use Unicode characters in console output
143
--color: Use color in console output
144
"""
145
```
146
147
## Usage Examples
148
149
### Jupyter Notebook Magic Commands
150
151
```python
152
# Load the extension
153
%load_ext pyinstrument
154
155
# Profile a single line
156
%pyinstrument expensive_function()
157
158
# Profile a cell with options
159
%%pyinstrument --renderer=html --render-option=timeline=true
160
data = load_large_dataset()
161
result = process_data(data)
162
visualize_results(result)
163
164
# Profile async code
165
%%pyinstrument --async_mode=enabled
166
await async_data_processing()
167
```
168
169
### Decorator Usage
170
171
```python
172
from pyinstrument import profile
173
174
# Simple decorator
175
@profile
176
def data_analysis():
177
load_data()
178
process_data()
179
generate_report()
180
181
data_analysis() # Results automatically printed
182
183
# Decorator with options
184
@profile(renderer=HTMLRenderer(timeline=True))
185
def complex_computation():
186
matrix_operations()
187
statistical_analysis()
188
189
complex_computation()
190
```
191
192
### Context Manager with Custom Renderer
193
194
```python
195
from pyinstrument import profile
196
from pyinstrument.renderers import HTMLRenderer
197
198
# Custom renderer context
199
html_renderer = HTMLRenderer(timeline=True, show_all=False)
200
201
with profile(renderer=html_renderer):
202
machine_learning_training()
203
model_evaluation()
204
```
205
206
### Command Line Profiling
207
208
```bash
209
# Basic script profiling
210
pyinstrument my_script.py
211
212
# With options
213
pyinstrument --renderer=html --outfile=profile.html my_script.py
214
215
# Module profiling
216
python -m pyinstrument -m my_module
217
218
# With timeline view
219
pyinstrument --timeline --renderer=html --outfile=timeline.html script.py
220
221
# JSON output for analysis
222
pyinstrument --renderer=json --outfile=profile.json script.py
223
```
224
225
### Django Integration
226
227
```python
228
# Django middleware example
229
from pyinstrument import Profiler
230
from django.conf import settings
231
232
class ProfilerMiddleware:
233
def __init__(self, get_response):
234
self.get_response = get_response
235
236
def __call__(self, request):
237
if settings.DEBUG and 'profile' in request.GET:
238
profiler = Profiler()
239
profiler.start()
240
241
response = self.get_response(request)
242
243
profiler.stop()
244
245
# Add profile to response
246
if request.GET.get('format') == 'html':
247
response.content = profiler.output_html().encode()
248
response['Content-Type'] = 'text/html'
249
else:
250
profiler.print()
251
252
return response
253
254
return self.get_response(request)
255
```
256
257
### FastAPI Integration
258
259
```python
260
from fastapi import FastAPI, Request
261
from pyinstrument import Profiler
262
263
app = FastAPI()
264
265
@app.middleware("http")
266
async def profile_middleware(request: Request, call_next):
267
if request.query_params.get("profile"):
268
profiler = Profiler(async_mode="enabled")
269
profiler.start()
270
271
response = await call_next(request)
272
273
profiler.stop()
274
275
# Return profile as HTML
276
if request.query_params.get("format") == "html":
277
html = profiler.output_html()
278
return Response(content=html, media_type="text/html")
279
else:
280
profiler.print()
281
282
return response
283
284
return await call_next(request)
285
```
286
287
### Programmatic Integration
288
289
```python
290
from pyinstrument import Profiler
291
from pyinstrument.renderers import JSONRenderer
292
import json
293
294
def profile_and_analyze(func, *args, **kwargs):
295
"""Profile a function call and return structured results."""
296
profiler = Profiler()
297
298
profiler.start()
299
result = func(*args, **kwargs)
300
profiler.stop()
301
302
# Get structured profiling data
303
json_renderer = JSONRenderer()
304
profile_data = json.loads(json_renderer.render(profiler.last_session))
305
306
return {
307
'function_result': result,
308
'profile_data': profile_data,
309
'execution_time': profiler.last_session.duration,
310
'cpu_time': profiler.last_session.cpu_time
311
}
312
313
# Usage
314
analysis = profile_and_analyze(expensive_computation, data_param)
315
print(f"Execution took {analysis['execution_time']:.3f} seconds")
316
```
317
318
## Types
319
320
```python { .api }
321
AsyncMode = Literal["enabled", "disabled", "strict"]
322
323
class Renderer:
324
"""Base renderer interface for output formatting."""
325
def render(self, session: Session) -> str: ...
326
327
ProfileContextOptions = TypedDict("ProfileContextOptions", {
328
"interval": float,
329
"async_mode": AsyncMode,
330
"use_timing_thread": bool | None,
331
"renderer": Renderer | None,
332
"target_description": str | None,
333
}, total=False)
334
```