or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-profiling.mdframework-integration.mdindex.mdoutput-rendering.mdsession-management.md

index.mddocs/

0

# Pyinstrument

1

2

A statistical Python profiler that provides detailed call stack analysis to help developers identify performance bottlenecks in their code. Pyinstrument uses low-overhead statistical sampling to capture execution data without significant performance impact, making it suitable for production environments.

3

4

## Package Information

5

6

- **Package Name**: pyinstrument

7

- **Language**: Python

8

- **Installation**: `pip install pyinstrument`

9

- **Repository**: https://github.com/joerick/pyinstrument

10

- **Documentation**: https://pyinstrument.readthedocs.io/

11

12

## Core Imports

13

14

```python

15

import pyinstrument

16

from pyinstrument import Profiler, __version__

17

```

18

19

For context manager/decorator usage:

20

21

```python

22

from pyinstrument import profile

23

```

24

25

## Basic Usage

26

27

### Simple Profiling with Context Manager

28

29

```python

30

from pyinstrument import Profiler

31

32

# Profile a block of code

33

profiler = Profiler()

34

profiler.start()

35

36

# Your code here

37

do_some_work()

38

39

profiler.stop()

40

profiler.print()

41

```

42

43

### Using as Context Manager

44

45

```python

46

from pyinstrument import Profiler

47

48

with Profiler() as profiler:

49

# Your code here

50

do_some_work()

51

52

# Results automatically printed to stderr

53

```

54

55

### Using as Decorator

56

57

```python

58

from pyinstrument import profile

59

60

@profile

61

def my_function():

62

# Your code here

63

do_some_work()

64

65

my_function() # Results automatically printed

66

```

67

68

## Architecture

69

70

Pyinstrument uses a statistical sampling approach to profiling:

71

72

- **Profiler**: Main interface for controlling profiling sessions

73

- **StackSampler**: Low-level component that periodically samples the call stack

74

- **Session**: Container for collected profiling data with metadata

75

- **Frame**: Represents individual stack frames in the call hierarchy

76

- **Renderers**: Output formatters for different display needs (console, HTML, JSON)

77

- **Processors**: Frame tree manipulation for filtering and aggregation

78

79

The profiler operates by setting up a signal handler or timing thread that periodically interrupts execution to capture the current call stack, building a statistical picture of where time is spent without the overhead of instrumenting every function call.

80

81

## Capabilities

82

83

### Core Profiling

84

85

Primary profiling functionality including session control, configuration options, and basic output generation. The main Profiler class provides the essential interface for capturing performance data.

86

87

```python { .api }

88

class Profiler:

89

def __init__(self, interval: float = 0.001, async_mode: str = "enabled", use_timing_thread: bool | None = None): ...

90

def start(self, caller_frame=None, target_description: str | None = None): ...

91

def stop(self) -> Session: ...

92

def reset(self): ...

93

def print(self, **kwargs): ...

94

def output_text(self, **kwargs) -> str: ...

95

def output_html(self) -> str: ...

96

```

97

98

[Core Profiling](./core-profiling.md)

99

100

### Output Rendering

101

102

Multiple output formats for displaying profiling results, including interactive HTML with timeline view, console text output with various formatting options, and export formats for integration with other tools.

103

104

```python { .api }

105

class ConsoleRenderer:

106

def __init__(self, unicode: bool = False, color: bool = False, show_all: bool = False, timeline: bool = False, **kwargs): ...

107

def render(self, session: Session) -> str: ...

108

109

class HTMLRenderer:

110

def __init__(self, timeline: bool = False, show_all: bool = False): ...

111

def render(self, session: Session) -> str: ...

112

def open_in_browser(self, session: Session): ...

113

```

114

115

[Output Rendering](./output-rendering.md)

116

117

### Session Management

118

119

Profiling session data structures and persistence functionality for saving and loading profile results, combining multiple sessions, and accessing detailed timing information.

120

121

```python { .api }

122

class Session:

123

def save(self, filename: str): ...

124

def load(filename: str) -> Session: ...

125

def to_json(self, include_frame_records: bool = True) -> dict: ...

126

def from_json(json_dict: dict) -> Session: ...

127

def combine(session1: Session, session2: Session) -> Session: ...

128

```

129

130

[Session Management](./session-management.md)

131

132

### Framework Integration

133

134

Built-in integration capabilities for popular Python frameworks and development environments including Jupyter notebooks, Django, FastAPI, and command-line usage.

135

136

```python { .api }

137

def load_ipython_extension(ipython): ...

138

139

# Context manager and decorator

140

def profile(**kwargs): ...

141

```

142

143

[Framework Integration](./framework-integration.md)

144

145

## Types

146

147

```python { .api }

148

from typing import IO, Any, Literal

149

import sys

150

import os

151

import types

152

153

__version__: str # Package version string (e.g., "5.1.1")

154

155

AsyncMode = Literal["enabled", "disabled", "strict"]

156

FlatTimeMode = Literal["self", "cumulative"]

157

PathOrStr = str | os.PathLike[str]

158

FrameRecordType = tuple[list[str], float]

159

160

class Session:

161

frame_records: list[FrameRecordType]

162

start_time: float

163

duration: float

164

min_interval: float

165

max_interval: float

166

sample_count: int

167

start_call_stack: list[str]

168

target_description: str

169

cpu_time: float

170

sys_path: list[str]

171

sys_prefixes: list[str]

172

173

class Frame:

174

identifier: str

175

time: float

176

children: list[Frame]

177

parent: Frame | None

178

file_path: str | None

179

function: str | None

180

line_no: int | None

181

absorbed_time: float

182

attributes: dict[str, float]