0
# Configuration and Output
1
2
Comprehensive configuration system supporting multiple profiling modes, output formats, and platform-specific options. Enables fine-tuned control over profiling behavior for different use cases from development to production.
3
4
## Capabilities
5
6
### Config Struct
7
8
Main configuration object controlling all aspects of py-spy behavior. Provides sensible defaults while allowing customization for specific profiling scenarios.
9
10
```rust { .api }
11
pub struct Config {
12
/// Process locking strategy during sampling
13
pub blocking: LockingStrategy,
14
/// Whether to profile native C/C++/Cython extensions
15
pub native: bool,
16
/// Sampling rate in Hz (samples per second)
17
pub sampling_rate: u64,
18
/// Output file format for record command
19
pub format: Option<FileFormat>,
20
/// Whether to include line numbers in output
21
pub show_line_numbers: bool,
22
/// Recording duration for record command
23
pub duration: RecordDuration,
24
/// Include idle/sleeping threads in results
25
pub include_idle: bool,
26
/// Include thread IDs in flamegraph output
27
pub include_thread_ids: bool,
28
/// Profile child processes and subprocesses
29
pub subprocesses: bool,
30
/// Only show threads holding the GIL
31
pub gil_only: bool,
32
/// Hide progress bar output
33
pub hide_progress: bool,
34
/// Capture stdout/stderr from spawned processes
35
pub capture_output: bool,
36
/// Output format for dump command (JSON vs text)
37
pub dump_json: bool,
38
/// Number of local variables to collect (0 = none)
39
pub dump_locals: u64,
40
/// Show full file paths vs shortened versions
41
pub full_filenames: bool,
42
/// Line number reporting mode
43
pub lineno: LineNo,
44
/// Console refresh rate for top command
45
pub refresh_seconds: f64,
46
// Additional private fields for CLI usage...
47
}
48
49
impl Config {
50
/// Creates Config from command line arguments
51
pub fn from_commandline() -> Config;
52
53
/// Creates Config from specific argument list
54
pub fn from_args(args: &[String]) -> clap::Result<Config>;
55
}
56
57
impl Default for Config {
58
fn default() -> Config;
59
}
60
```
61
62
**Default Configuration:**
63
64
```rust
65
Config {
66
blocking: LockingStrategy::Lock,
67
native: false,
68
sampling_rate: 100,
69
format: None,
70
show_line_numbers: false,
71
duration: RecordDuration::Unlimited,
72
include_idle: false,
73
include_thread_ids: false,
74
subprocesses: false,
75
gil_only: false,
76
hide_progress: false,
77
capture_output: true,
78
dump_json: false,
79
dump_locals: 0,
80
full_filenames: false,
81
lineno: LineNo::LastInstruction,
82
refresh_seconds: 1.0,
83
// CLI-specific fields omitted...
84
}
85
```
86
87
### Locking Strategy
88
89
Controls how py-spy interacts with the target process during sampling, affecting both accuracy and performance impact.
90
91
```rust { .api }
92
pub enum LockingStrategy {
93
/// Standard mode: pause process during sampling for accurate results
94
Lock,
95
96
/// Non-blocking mode: sample without pausing (lower impact, potential inaccuracy)
97
NonBlocking,
98
99
/// Process is already locked by another tool
100
AlreadyLocked,
101
}
102
```
103
104
**Usage Examples:**
105
106
```rust
107
// Standard mode - most accurate, slight performance impact
108
let mut config = Config::default();
109
config.blocking = LockingStrategy::Lock;
110
111
// Production mode - minimal impact, potential sampling errors
112
let mut config = Config::default();
113
config.blocking = LockingStrategy::NonBlocking;
114
```
115
116
### Output Formats
117
118
Multiple output formats for different analysis tools and workflows.
119
120
```rust { .api }
121
pub enum FileFormat {
122
/// SVG flamegraph for visual analysis
123
flamegraph,
124
125
/// Raw flamegraph data (text format)
126
raw,
127
128
/// Speedscope JSON format for speedscope.app
129
speedscope,
130
131
/// Chrome trace format for chrome://tracing
132
chrometrace,
133
}
134
135
impl std::str::FromStr for FileFormat {
136
type Err = String;
137
fn from_str(s: &str) -> Result<Self, Self::Err>;
138
}
139
```
140
141
**Format Descriptions:**
142
143
- **flamegraph**: Interactive SVG visualization showing call stack hierarchy and time distribution
144
- **speedscope**: JSON format compatible with speedscope.app for detailed analysis
145
- **chrometrace**: JSON format for Chrome DevTools or Perfetto for timeline analysis
146
- **raw**: Text format compatible with flamegraph.pl script for custom processing
147
148
### Recording Duration
149
150
Controls how long profiling sessions run, useful for automated profiling and resource management.
151
152
```rust { .api }
153
pub enum RecordDuration {
154
/// Continue recording until manually stopped (Ctrl-C)
155
Unlimited,
156
157
/// Record for specified number of seconds
158
Seconds(u64),
159
}
160
```
161
162
**Usage Examples:**
163
164
```rust
165
// Short burst profiling
166
let mut config = Config::default();
167
config.duration = RecordDuration::Seconds(30);
168
169
// Continuous profiling until stopped
170
let mut config = Config::default();
171
config.duration = RecordDuration::Unlimited;
172
```
173
174
### Line Number Reporting
175
176
Controls how line numbers are reported in stack traces.
177
178
```rust { .api }
179
pub enum LineNo {
180
/// Don't include line numbers
181
NoLine,
182
183
/// Use first line of function definition
184
First,
185
186
/// Use line of last executed instruction (default)
187
LastInstruction,
188
}
189
```
190
191
## Configuration Patterns
192
193
### Development Profiling
194
195
Optimized for detailed analysis during development with comprehensive information collection.
196
197
```rust
198
use py_spy::{Config, LockingStrategy, RecordDuration, LineNo};
199
200
fn development_config() -> Config {
201
let mut config = Config::default();
202
config.blocking = LockingStrategy::Lock; // Accurate sampling
203
config.show_line_numbers = true; // Include line numbers
204
config.include_idle = false; // Skip idle threads
205
config.sampling_rate = 100; // Standard rate
206
config.lineno = LineNo::LastInstruction; // Precise line info
207
config.full_filenames = true; // Full paths for debugging
208
config
209
}
210
```
211
212
### Production Profiling
213
214
Minimizes performance impact while collecting useful profiling data.
215
216
```rust
217
use py_spy::{Config, LockingStrategy, RecordDuration};
218
219
fn production_config() -> Config {
220
let mut config = Config::default();
221
config.blocking = LockingStrategy::NonBlocking; // Minimal impact
222
config.sampling_rate = 50; // Lower sampling rate
223
config.duration = RecordDuration::Seconds(60); // Limited duration
224
config.hide_progress = true; // No UI interference
225
config.gil_only = true; // Focus on active threads
226
config
227
}
228
```
229
230
### Native Extension Analysis
231
232
Configured for profiling applications using C/C++/Cython extensions.
233
234
```rust
235
use py_spy::{Config, LockingStrategy};
236
237
fn native_extension_config() -> Config {
238
let mut config = Config::default();
239
config.native = true; // Enable native profiling
240
config.blocking = LockingStrategy::Lock; // Required for native traces
241
config.show_line_numbers = true; // Helpful for mixed code
242
config.sampling_rate = 200; // Higher rate for detail
243
config
244
}
245
```
246
247
### Subprocess Profiling
248
249
Configured for profiling applications that spawn child processes.
250
251
```rust
252
use py_spy::{Config, RecordDuration};
253
254
fn subprocess_config() -> Config {
255
let mut config = Config::default();
256
config.subprocesses = true; // Follow child processes
257
config.include_thread_ids = true; // Distinguish processes
258
config.duration = RecordDuration::Seconds(120); // Longer duration
259
config.sampling_rate = 50; // Manage overhead
260
config
261
}
262
```
263
264
## Output Format Details
265
266
### Flamegraph Output
267
268
SVG format providing interactive visualization of call stack hierarchies.
269
270
```rust
271
use py_spy::{Config, FileFormat};
272
273
let mut config = Config::default();
274
config.format = Some(FileFormat::flamegraph);
275
config.show_line_numbers = true; // Include line info in frames
276
config.include_thread_ids = false; // Clean visualization
277
```
278
279
**Features:**
280
- Interactive SVG with zoom and search
281
- Proportional width showing time spent
282
- Hover tooltips with frame information
283
- Opens automatically in browser on macOS
284
285
### Speedscope Output
286
287
JSON format optimized for detailed analysis in speedscope.app.
288
289
```rust
290
use py_spy::{Config, FileFormat};
291
292
let mut config = Config::default();
293
config.format = Some(FileFormat::speedscope);
294
config.include_thread_ids = true; // Thread separation
295
config.show_line_numbers = true; // Detailed frame info
296
```
297
298
**Features:**
299
- Timeline view showing execution over time
300
- Left Heavy view for hotspot identification
301
- Sandwich view for caller/callee analysis
302
- Load at https://www.speedscope.app/
303
304
### Chrome Trace Output
305
306
JSON format compatible with Chrome DevTools and Perfetto.
307
308
```rust
309
use py_spy::{Config, FileFormat};
310
311
let mut config = Config::default();
312
config.format = Some(FileFormat::chrometrace);
313
config.include_thread_ids = true; // Thread-based visualization
314
config.sampling_rate = 1000; // High resolution
315
```
316
317
**Features:**
318
- Timeline visualization with thread separation
319
- Precise timing information
320
- Compatible with chrome://tracing
321
- Works with https://ui.perfetto.dev/
322
323
### Raw Output
324
325
Text format compatible with flamegraph.pl and custom processing tools.
326
327
```rust
328
use py_spy::{Config, FileFormat};
329
330
let mut config = Config::default();
331
config.format = Some(FileFormat::raw);
332
config.full_filenames = true; // Complete paths
333
config.show_line_numbers = true; // Line information
334
```
335
336
**Features:**
337
- Plain text format for scripting
338
- Compatible with flamegraph.pl
339
- Easy parsing for custom analysis
340
- Suitable for CI/CD integration
341
342
## Platform-Specific Configuration
343
344
### Linux Configuration
345
346
```rust
347
// Core dump analysis (Linux only)
348
let mut config = Config::default();
349
config.core_filename = Some("/path/to/core.dump".to_string());
350
351
// Docker-aware profiling
352
config.blocking = LockingStrategy::NonBlocking; // May be required in containers
353
```
354
355
### macOS Configuration
356
357
```rust
358
// macOS requires more conservative settings
359
let mut config = Config::default();
360
config.sampling_rate = 50; // Lower rate for stability
361
// Note: Requires root privileges (sudo)
362
```
363
364
### Windows Configuration
365
366
```rust
367
// Windows-specific optimizations
368
let mut config = Config::default();
369
config.sampling_rate = 100; // Standard rate works well
370
config.hide_progress = true; // Better console compatibility
371
```
372
373
## Error Handling
374
375
Configuration errors are typically reported through clap's error system when using `from_args()`, or through Result types in the library API.
376
377
```rust
378
use py_spy::Config;
379
380
// Handle CLI parsing errors
381
let config = match Config::from_args(&args) {
382
Ok(config) => config,
383
Err(e) => {
384
eprintln!("Configuration error: {}", e);
385
std::process::exit(1);
386
}
387
};
388
389
// Validate configuration compatibility
390
if config.native && config.blocking == LockingStrategy::NonBlocking {
391
eprintln!("Error: Native profiling requires blocking mode");
392
std::process::exit(1);
393
}
394
```