-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyspy_profile.py
More file actions
75 lines (63 loc) · 1.96 KB
/
Copy pathpyspy_profile.py
File metadata and controls
75 lines (63 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from __future__ import annotations
import os
import pathlib
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
@dataclass
class PySpySession:
process: subprocess.Popen[bytes]
output_path: pathlib.Path
def start_py_spy_profile(
*,
enabled: bool,
label: str,
output_path: pathlib.Path | None = None,
sample_rate: int = 100,
) -> PySpySession | None:
if not enabled:
return None
exe = shutil.which("py-spy")
if exe is None:
print("Warning: --profile requested but py-spy is not installed or not on PATH.", file=sys.stderr, flush=True)
return None
if output_path is None:
out_dir = pathlib.Path.cwd() / "profiles"
out_dir.mkdir(parents=True, exist_ok=True)
output_path = out_dir / f"{label}_{time.strftime('%Y%m%d_%H%M%S')}.svg"
else:
output_path.parent.mkdir(parents=True, exist_ok=True)
cmd = [
exe,
"record",
"--pid",
str(os.getpid()),
"--rate",
str(sample_rate),
"--output",
str(output_path),
]
try:
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception as exc:
print(f"Warning: failed to start py-spy profiler: {exc}", file=sys.stderr, flush=True)
return None
print(f"[profile] py-spy recording to {output_path}", file=sys.stderr, flush=True)
return PySpySession(process=proc, output_path=output_path)
def stop_py_spy_profile(session: PySpySession | None) -> None:
if session is None:
return
proc = session.process
if proc.poll() is None:
try:
proc.terminate()
proc.wait(timeout=5.0)
except Exception:
try:
proc.kill()
proc.wait(timeout=2.0)
except Exception:
pass
print(f"[profile] py-spy output saved to {session.output_path}", file=sys.stderr, flush=True)