0
# Core Profiling
1
2
Primary profiling functionality providing the main interface for capturing and analyzing performance data. The Profiler class offers comprehensive control over profiling sessions with support for various execution modes and configuration options.
3
4
## Capabilities
5
6
### Profiler Class
7
8
The main profiling interface that manages sampling configuration, session lifecycle, and basic output generation.
9
10
```python { .api }
11
from typing import IO, Any, Literal
12
import sys
13
import os
14
import types
15
16
class Profiler:
17
"""
18
The main profiler class for capturing call stack profiles.
19
20
Attributes:
21
interval (float): Sampling interval in seconds
22
async_mode (AsyncMode): How to handle async/await code
23
last_session (Session | None): Most recent profiling session
24
is_running (bool): Whether profiler is currently active
25
"""
26
27
def __init__(
28
self,
29
interval: float = 0.001,
30
async_mode: AsyncMode = "enabled",
31
use_timing_thread: bool | None = None
32
):
33
"""
34
Initialize profiler with configuration options.
35
36
Args:
37
interval: Minimum time between samples in seconds (default: 0.001)
38
async_mode: How to handle async/await - "enabled", "disabled", or "strict"
39
use_timing_thread: Use separate thread for timing (helpful in some Docker environments)
40
"""
41
42
def start(
43
self,
44
caller_frame: types.FrameType | None = None,
45
target_description: str | None = None
46
) -> None:
47
"""
48
Start profiling session.
49
50
Args:
51
caller_frame: Override default caller frame detection
52
target_description: Description for this profiling session
53
54
Raises:
55
RuntimeError: If profiler is already running
56
"""
57
58
def stop(self) -> Session:
59
"""
60
Stop profiling and return captured session data.
61
62
Returns:
63
Session object containing profiling results
64
65
Raises:
66
RuntimeError: If profiler is not currently running
67
"""
68
69
def reset(self) -> None:
70
"""
71
Reset profiler state and clear last_session data.
72
"""
73
74
@property
75
def is_running(self) -> bool:
76
"""
77
Check if profiler is currently running.
78
79
Returns:
80
True if profiler is actively collecting samples, False otherwise
81
"""
82
83
def print(
84
self,
85
file: IO[str] = sys.stdout,
86
*,
87
unicode: bool | None = None,
88
color: bool | None = None,
89
show_all: bool = False,
90
timeline: bool = False,
91
time: Literal["seconds", "percent_of_total"] = "seconds",
92
flat: bool = False,
93
flat_time: FlatTimeMode = "self",
94
short_mode: bool = False,
95
processor_options: dict[str, Any] | None = None,
96
**kwargs
97
) -> None:
98
"""
99
Print profiling results to console.
100
101
Args:
102
file: Output stream (default: sys.stdout)
103
unicode: Use Unicode characters for display
104
color: Use ANSI color codes
105
show_all: Show all frames including library code
106
timeline: Show timeline view of execution
107
time: Display time as "seconds" or "percent_of_total"
108
flat: Show flat profile instead of call tree
109
flat_time: For flat mode - "self" or "cumulative" time
110
short_mode: Use compact output format
111
processor_options: Frame processing configuration
112
"""
113
114
def output_text(
115
self,
116
unicode: bool = False,
117
color: bool = False,
118
show_all: bool = False,
119
timeline: bool = False,
120
time: Literal["seconds", "percent_of_total"] = "seconds",
121
flat: bool = False,
122
flat_time: FlatTimeMode = "self",
123
short_mode: bool = False,
124
processor_options: dict[str, Any] | None = None
125
) -> str:
126
"""
127
Generate profiling results as formatted text string.
128
129
Args:
130
unicode: Use Unicode characters for display
131
color: Use ANSI color codes
132
show_all: Show all frames including library code
133
timeline: Show timeline view of execution
134
time: Display time as "seconds" or "percent_of_total"
135
flat: Show flat profile instead of call tree
136
flat_time: For flat mode - "self" or "cumulative" time
137
short_mode: Use compact output format
138
processor_options: Frame processing configuration
139
140
Returns:
141
Formatted profiling output as string
142
"""
143
144
def output_html(self) -> str:
145
"""
146
Generate profiling results as interactive HTML.
147
148
Returns:
149
HTML string with interactive profiling interface
150
"""
151
152
def write_html(
153
self,
154
path: str | os.PathLike[str],
155
timeline: bool = False,
156
show_all: bool = False
157
) -> None:
158
"""
159
Write HTML profiling results to file.
160
161
Args:
162
path: Output file path
163
timeline: Include timeline view
164
show_all: Show all frames including library code
165
"""
166
167
def open_in_browser(self, timeline: bool = False) -> None:
168
"""
169
Open profiling results in web browser.
170
171
Args:
172
timeline: Show timeline view
173
"""
174
```
175
176
### Context Manager Support
177
178
The Profiler class supports Python's context manager protocol for automatic session management.
179
180
```python { .api }
181
def __enter__(self) -> Profiler:
182
"""
183
Enter context manager, automatically starting profiling.
184
185
Returns:
186
The Profiler instance for method chaining
187
"""
188
189
def __exit__(
190
self,
191
exc_type: type[BaseException] | None,
192
exc_value: BaseException | None,
193
traceback: types.TracebackType | None
194
) -> None:
195
"""
196
Exit context manager, automatically stopping profiling.
197
198
Args:
199
exc_type: Exception type if exception occurred
200
exc_value: Exception instance if exception occurred
201
traceback: Traceback object if exception occurred
202
"""
203
```
204
205
### Usage Examples
206
207
#### Basic Profiling Session
208
209
```python
210
from pyinstrument import Profiler
211
212
profiler = Profiler(interval=0.001) # Sample every 1ms
213
profiler.start()
214
215
# Your code to profile
216
result = expensive_calculation()
217
218
session = profiler.stop()
219
profiler.print()
220
```
221
222
#### Context Manager Usage
223
224
```python
225
from pyinstrument import Profiler
226
227
with Profiler() as profiler:
228
# Code is automatically profiled
229
process_large_dataset()
230
231
# Results available in profiler.last_session
232
```
233
234
#### Async Mode Configuration
235
236
```python
237
# For async/await code
238
profiler = Profiler(async_mode="enabled")
239
240
# To disable async handling
241
profiler = Profiler(async_mode="disabled")
242
243
# Strict async context mode
244
profiler = Profiler(async_mode="strict")
245
```
246
247
#### Custom Output Options
248
249
```python
250
profiler = Profiler()
251
with profiler:
252
do_work()
253
254
# Different output formats
255
profiler.print(color=True, unicode=True, show_all=True)
256
html_output = profiler.output_html()
257
text_output = profiler.output_text(timeline=True)
258
```