дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
feat(profiler): profile Python runs with yappi (threads, asyncio) (#7466)
Profile on a Python run configuration uses yappi when the run's interpreter can import it: Automatic picks yappi, else py-spy where it can sample without root, else cProfile, and Settings › Python › Profiler gains a yappi choice (missing yappi offers `python -m pip install yappi`, or only the homepage under uv/poetry). yappi runs through python_profile.py with the wall clock and builtins, so a coroutine's time includes its awaits and every thread is profiled; the launcher writes the merged profile.pstats plus one pstats per thread and threads.json (busiest 64), converted to cProfile's call-count order and built-in names. Non-daemon threads and pools are waited for before saving, except after Stop. The Profiler view gets a thread selector (All threads merged, then each thread) when a run has two or more threads. The Rust CI job installs yappi 1.7.6 in a venv on GitHub-hosted runners for the real-interpreter tests. Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
9f63ea75fe
коміт
d1c07306e9
25 files changed
+924
-56
No files matched your search
@@ -217,6 +217,23 @@ jobs:
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
# python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without
|
||||
# YAPPI_PYTHON those tests return early.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.environment == 'github-hosted'
|
||||
id: yappi-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install yappi for the Python profiler tests
|
||||
if: steps.yappi-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.yappi-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/yappi-venv"
|
||||
venv_py="$RUNNER_TEMP/yappi-venv/bin/python"
|
||||
[ -x "$venv_py" ] || venv_py="$RUNNER_TEMP/yappi-venv/Scripts/python.exe"
|
||||
"$venv_py" -m pip install yappi==1.7.6
|
||||
echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV"
|
||||
# python_memray.rs profiles real runs. memray has no Windows build.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
|
||||
|
||||
@@ -1921,8 +1921,9 @@ pub struct PythonSettings {
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the
|
||||
/// interpreter can import it, else py-spy where it is installed and samples without root, else
|
||||
/// cProfile), `cprofile`, `py-spy` or `yappi`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! | runtime | profiler | output |
|
||||
//! |---|---|---|
|
||||
//! | Node.js (scripts, npm scripts) | `node --cpu-prof` (via `NODE_OPTIONS`) | `.cpuprofile` JSON |
|
||||
//! | Python | cProfile (`python_profile.py`), or `py-spy record --format raw` | pstats, or collapsed stacks |
|
||||
//! | Python | yappi or cProfile (`python_profile.py`), or `py-spy record --format raw` | pstats, or collapsed stacks |
|
||||
//! | Python allocations (macOS/Linux) | memray (`python_profile.py`), then `memray transform csv` | CSV |
|
||||
//! | JVM applications | async-profiler agent (`JAVA_TOOL_OPTIONS`) | collapsed stacks |
|
||||
//! | native / `cargo run` (Linux) | `perf record -g`, then `perf script` | perf script text |
|
||||
@@ -113,7 +113,7 @@ pub struct CallEdge {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Profile {
|
||||
/// `node --cpu-prof`, `py-spy`, `async-profiler`, `perf`.
|
||||
/// `node --cpu-prof`, `yappi`, `cProfile`, `py-spy`, `async-profiler`, `perf`.
|
||||
pub profiler: String,
|
||||
/// `ms` (time-weighted), `samples` (sample or live-object counts) or `bytes` (allocated).
|
||||
pub unit: String,
|
||||
@@ -127,6 +127,18 @@ pub struct Profile {
|
||||
/// Exact caller → callee totals of a call-graph profile; its call tree is then rebuilt
|
||||
/// from them, so below the first level it is an estimate. Empty for sampled profiles.
|
||||
pub calls: Vec<CallEdge>,
|
||||
/// The threads of a yappi run, busiest first; empty when the profiler does not tell them apart.
|
||||
pub threads: Vec<ProfileThread>,
|
||||
}
|
||||
|
||||
/// A thread of a yappi run. Its own profile is `collect`ed with the spec's `thread` set to `id`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProfileThread {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
/// Seconds the thread ran (wall clock).
|
||||
pub total: f64,
|
||||
}
|
||||
|
||||
/// Where a prepared run's profile will be, and how to read it.
|
||||
@@ -142,8 +154,9 @@ pub enum ProfileSpec {
|
||||
/// Relative source files of a `pstats` file resolve against `root`, then its directory.
|
||||
SnapshotFile { path: IpcPath, root: Option<IpcPath> },
|
||||
/// What `python_profile.py` wrote in `dir` for a profiled Python run: `profile.pstats`.
|
||||
/// Relative source files resolve against `root`.
|
||||
PythonRun { profiler: String, dir: IpcPath, root: IpcPath },
|
||||
/// Relative source files resolve against `root`. `thread`: a yappi run's thread to show
|
||||
/// (`Profile::threads`), else all threads merged.
|
||||
PythonRun { profiler: String, dir: IpcPath, root: IpcPath, thread: Option<u32> },
|
||||
/// The `memray.bin` capture `python_profile.py` wrote in `dir`, read with
|
||||
/// `<python> -m memray transform csv`: what was allocated at the memory peak.
|
||||
/// Relative source files resolve against `root`, where the command runs.
|
||||
@@ -181,6 +194,15 @@ fn files_with_ext(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The threads `python_profile.py` listed in `threads.json` (yappi runs), busiest first.
|
||||
fn threads(dir: &Path) -> Vec<ProfileThread> {
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("threads.json")) else { return Vec::new() };
|
||||
let mut threads: Vec<ProfileThread> = serde_json::from_str(&text).unwrap_or_default();
|
||||
threads.retain(|t| dir.join(format!("thread-{}.pstats", t.id)).is_file());
|
||||
threads.sort_by(|a, b| b.total.total_cmp(&a.total).then(a.id.cmp(&b.id)));
|
||||
threads
|
||||
}
|
||||
|
||||
fn nothing_recorded(what: &str) -> IdeError {
|
||||
let mut msg = format!("The run produced no profile ({what}).");
|
||||
if cfg!(target_os = "macos") && what.contains("py-spy") {
|
||||
@@ -244,15 +266,17 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
ProfileSpec::PythonRun { profiler, dir, root } => {
|
||||
let bytes = std::fs::read(Path::new(dir.as_ref()).join("profile.pstats")).map_err(|e| match e.kind() {
|
||||
ProfileSpec::PythonRun { profiler, dir, root, thread } => {
|
||||
let file = thread.map_or_else(|| "profile.pstats".to_owned(), |t| format!("thread-{t}.pstats"));
|
||||
let bytes = std::fs::read(Path::new(dir.as_ref()).join(file)).map_err(|e| match e.kind() {
|
||||
// A run that was killed (a second Stop) or left through `os._exit`.
|
||||
std::io::ErrorKind::NotFound => nothing_recorded(&format!("{profiler} wrote no profile")),
|
||||
_ => IdeError::invalid(format!("Cannot read the {profiler} profile: {e}")),
|
||||
})?;
|
||||
let bases: [&Path; 2] = [root.as_ref(), dir.as_ref()];
|
||||
let profile = pstats::read(&bytes, &bases, profiler)
|
||||
let mut profile = pstats::read(&bytes, &bases, profiler)
|
||||
.map_err(|e| IdeError::invalid(format!("Cannot read the {profiler} profile: {e}")))?;
|
||||
profile.threads = threads(dir.as_ref());
|
||||
if profile.methods.is_empty() {
|
||||
return Err(nothing_recorded(&format!("{profiler} recorded no calls")));
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ use crate::{ProfileMode, ProfilePrepared, ProfileSpec, ProfilerInstall};
|
||||
use ide_run::RunConfig;
|
||||
use ide_run::wrap::{self, program_name};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
const ASYNC_PROFILER_HOME: &str = "https://github.com/async-profiler/async-profiler/releases";
|
||||
const YAPPI_HOME: &str = "https://github.com/sumerc/yappi";
|
||||
const MEMRAY_HOME: &str = "https://github.com/bloomberg/memray";
|
||||
const PY_SPY_HOME: &str = "https://github.com/benfred/py-spy";
|
||||
/// Starts `-c` code that imports memray without the working directory on `sys.path`: a project's
|
||||
@@ -105,25 +107,23 @@ fn python(
|
||||
let beside =
|
||||
Path::new(&py.interpreter[0]).parent().map(|d| d.join(if cfg!(windows) { "py-spy.exe" } else { "py-spy" }));
|
||||
let found = beside.filter(|p| p.is_file()).or_else(|| wrap::find_tool("py-spy", config, dir, root));
|
||||
// yappi imported by the interpreter itself: it profiles every thread and coroutine.
|
||||
let yappi = match profiler {
|
||||
"cprofile" | "py-spy" => false,
|
||||
_ => has_yappi(config, dir, &py),
|
||||
};
|
||||
if yappi {
|
||||
return python_launcher(config, dir, out, py, "yappi", "yappi");
|
||||
}
|
||||
if profiler == "yappi" {
|
||||
return missing_python_tool("yappi", YAPPI_HOME, dir, &py);
|
||||
}
|
||||
let py_spy = match (profiler, found) {
|
||||
("cprofile", _) => return cprofile(config, dir, out, py),
|
||||
("py-spy", Some(found)) => found,
|
||||
// On macOS py-spy samples only as root, which a run from the IDE isn't.
|
||||
(_, Some(found)) if !cfg!(target_os = "macos") => found,
|
||||
("py-spy", None) => {
|
||||
let install = (py.manager.is_none()).then(|| {
|
||||
let mut argv = py.interpreter.clone();
|
||||
argv.extend([s("-m"), s("pip"), s("install"), s("py-spy")]);
|
||||
let (command, args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default();
|
||||
ProfilerInstall { command, args, cwd: Some(dir.to_path_buf().into()) }
|
||||
});
|
||||
return ProfilePrepared::MissingTool {
|
||||
tool: s("py-spy"),
|
||||
message: s("Profiling Python with py-spy needs py-spy."),
|
||||
install,
|
||||
homepage: Some(PY_SPY_HOME.into()),
|
||||
};
|
||||
}
|
||||
("py-spy", None) => return missing_python_tool("py-spy", PY_SPY_HOME, dir, &py),
|
||||
_ => return cprofile(config, dir, out, py),
|
||||
};
|
||||
let mut args = vec![
|
||||
@@ -150,6 +150,56 @@ fn python(
|
||||
ready("py-spy", launch, spec)
|
||||
}
|
||||
|
||||
/// Whether the run's interpreter (`uv run python`, a virtualenv's) can import yappi. A probe
|
||||
/// that takes longer than `PROBE_SECS` (a project manager syncing its environment) counts as no.
|
||||
fn has_yappi(config: &RunConfig, dir: &Path, py: &wrap::PythonCommand) -> bool {
|
||||
const PROBE_SECS: u64 = 20;
|
||||
let Some((command, args)) = py.interpreter.split_first() else { return false };
|
||||
let Ok(mut child) = ide_core::process::prepare(&mut Command::new(command))
|
||||
.args(args)
|
||||
.args(["-c", "import yappi"])
|
||||
.current_dir(dir)
|
||||
.envs(&config.env)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(PROBE_SECS);
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => return status.success(),
|
||||
Ok(None) if std::time::Instant::now() < deadline => {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20))
|
||||
}
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Profiling needs `tool`, which `pip install` puts into the interpreter's environment;
|
||||
/// where a project manager (uv, poetry) owns the environment the user adds it there.
|
||||
fn missing_python_tool(tool: &str, homepage: &str, dir: &Path, py: &wrap::PythonCommand) -> ProfilePrepared {
|
||||
let install = py.manager.is_none().then(|| {
|
||||
let mut argv = py.interpreter.clone();
|
||||
argv.extend([s("-m"), s("pip"), s("install"), s(tool)]);
|
||||
let (command, args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default();
|
||||
ProfilerInstall { command, args, cwd: Some(dir.to_path_buf().into()) }
|
||||
});
|
||||
ProfilePrepared::MissingTool {
|
||||
tool: s(tool),
|
||||
message: format!("Profiling Python with {tool} needs {tool}."),
|
||||
install,
|
||||
homepage: Some(homepage.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the program with memray tracking its allocations, through the same launcher as cProfile.
|
||||
fn memray(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -> ProfilePrepared {
|
||||
if cfg!(windows) {
|
||||
@@ -234,8 +284,12 @@ fn python_launcher(
|
||||
}
|
||||
argv.extend(py.target);
|
||||
(launch.command, launch.args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default();
|
||||
let spec =
|
||||
ProfileSpec::PythonRun { profiler: s(profiler), dir: out.to_path_buf().into(), root: dir.to_path_buf().into() };
|
||||
let spec = ProfileSpec::PythonRun {
|
||||
profiler: s(profiler),
|
||||
dir: out.to_path_buf().into(),
|
||||
root: dir.to_path_buf().into(),
|
||||
thread: None,
|
||||
};
|
||||
ready(profiler, launch, spec)
|
||||
}
|
||||
|
||||
@@ -480,7 +534,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("python_profile.py")).unwrap(), PYTHON_LAUNCHER);
|
||||
let (out, root) = (dir.path().to_path_buf().into(), dir.path().to_path_buf().into());
|
||||
assert_eq!(spec, ProfileSpec::PythonRun { profiler: "cProfile".into(), dir: out, root });
|
||||
assert_eq!(spec, ProfileSpec::PythonRun { profiler: "cProfile".into(), dir: out, root, thread: None });
|
||||
assert_eq!(launch.extras.stop_command.is_some(), cfg!(windows));
|
||||
|
||||
// py-spy installed: Automatic takes it except on macOS, where it would need root.
|
||||
@@ -491,6 +545,27 @@ mod tests {
|
||||
assert_eq!(python_plan(&c, dir.path(), "py-spy").0, "py-spy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_yappi_without_it_offers_to_install_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = dir.path().join("python").to_string_lossy().into_owned();
|
||||
std::fs::write(&python, "").unwrap();
|
||||
let c = cfg("python", &python, &["main.py"]);
|
||||
match prepare(dir.path(), &c, dir.path(), ProfileMode::Cpu, "yappi") {
|
||||
ProfilePrepared::MissingTool { tool, install: Some(i), .. } => {
|
||||
assert_eq!(tool, "yappi");
|
||||
assert_eq!((i.command, i.args), (python, v(&["-m", "pip", "install", "yappi"])));
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// Under uv the project's manager owns the environment: no pip command.
|
||||
let uv = cfg("python", "uv", &["run", "python", "main.py"]);
|
||||
assert!(matches!(
|
||||
prepare(dir.path(), &uv, dir.path(), ProfileMode::Cpu, "yappi"),
|
||||
ProfilePrepared::MissingTool { install: None, .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cprofile_keeps_the_configurations_interpreter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""Runs a script, module (-m) or code (-c) under a profiler for the IDE's Profile action.
|
||||
|
||||
Usage: python python_profile.py (cprofile | memray) <out dir> [--stop <pipe>] (<script> | -m <module> | -c <code>) [args...]
|
||||
Usage: python python_profile.py (cprofile | yappi | memray) <out dir> [--stop <pipe>] (<script> | -m <module> | -c <code>) [args...]
|
||||
|
||||
Runs the target as `python <target>` would (it is `__main__` until the process exits, its
|
||||
exit code is kept) and writes <out>/profile.pstats (cprofile) or <out>/memray.bin when it ends, also when Stop interrupts
|
||||
it (KeyboardInterrupt).
|
||||
exit code is kept) and writes <out>/profile.pstats (cprofile, yappi) or <out>/memray.bin when
|
||||
it ends, also when Stop interrupts it (KeyboardInterrupt). yappi (wall clock, so a coroutine's
|
||||
time includes its awaits, every thread) also writes <out>/thread-<id>.pstats per thread and
|
||||
<out>/threads.json.
|
||||
`--stop`: where Stop cannot interrupt the process itself (Windows), its stop command opens
|
||||
this named pipe (a FIFO elsewhere); the profile is then saved and the run interrupted.
|
||||
"""
|
||||
@@ -116,6 +118,74 @@ def cprofile(out):
|
||||
return profiler.enable, save
|
||||
|
||||
|
||||
WATCHER = "openidea-stop-watcher"
|
||||
# A yappi run lists at most this many threads (the busiest); the merged profile has them all.
|
||||
MAX_THREADS = 64
|
||||
|
||||
|
||||
def yappi_profiler(out):
|
||||
import json
|
||||
import marshal
|
||||
|
||||
import yappi
|
||||
|
||||
yappi.set_context_name_callback(lambda: threading.current_thread().name)
|
||||
yappi.set_clock_type("wall")
|
||||
launcher = os.path.abspath(__file__)
|
||||
|
||||
def start():
|
||||
# Every thread that starts afterwards; the watcher and this launcher's own frames are older.
|
||||
yappi.start(builtins=True)
|
||||
|
||||
def key(k):
|
||||
# A built-in has no file: yappi names its module, cProfile writes `~`.
|
||||
file, line, name = k
|
||||
if line or os.path.isabs(file) or file == "~" or os.sep in file:
|
||||
return k
|
||||
if not name.startswith("<"):
|
||||
name = "<built-in function %s>" % name if file == "builtins" else "<built-in method %s.%s>" % (file, name)
|
||||
return ("~", 0, name)
|
||||
|
||||
def write(stats, name):
|
||||
"""Saves `stats` as cProfile's pstats: yappi writes (total calls, primitive calls) where
|
||||
cProfile has (primitive, total), and names built-ins by module."""
|
||||
path = os.path.join(out, name)
|
||||
stats.save(path, type="pstat")
|
||||
with open(path, "rb") as f:
|
||||
table = marshal.load(f)
|
||||
fixed = {}
|
||||
for k, (a, b, tt, ct, callers) in table.items():
|
||||
if k[0] == launcher:
|
||||
continue
|
||||
callers = {key(c): v for c, v in callers.items() if c[0] != launcher}
|
||||
fixed[key(k)] = (b, a, tt, ct, callers)
|
||||
with open(path, "wb") as f:
|
||||
marshal.dump(fixed, f)
|
||||
|
||||
def save():
|
||||
yappi.stop()
|
||||
write(yappi.get_func_stats(), "profile.pstats")
|
||||
threads = [t for t in yappi.get_thread_stats() if t.name != WATCHER]
|
||||
threads.sort(key=lambda t: -t.ttot)
|
||||
listed = []
|
||||
for t in threads[:MAX_THREADS]:
|
||||
write(yappi.get_func_stats(filter={"ctx_id": t.id}), "thread-%d.pstats" % t.id)
|
||||
listed.append({"id": t.id, "name": t.name, "total": t.ttot})
|
||||
with open(os.path.join(out, "threads.json"), "w") as f:
|
||||
json.dump(listed, f)
|
||||
|
||||
return start, save
|
||||
|
||||
|
||||
def finish_threads():
|
||||
"""Lets non-daemon threads (and thread pools) end first, as Python does when the main
|
||||
thread returns, so their work is in the profile."""
|
||||
try:
|
||||
threading._shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def memray_allocations(out):
|
||||
import memray
|
||||
|
||||
@@ -131,16 +201,21 @@ def main():
|
||||
stop_file = None
|
||||
if target[:1] == ["--stop"]:
|
||||
stop_file, target = target[1], target[2:]
|
||||
start, save = {"cprofile": cprofile, "memray": memray_allocations}[profiler](out)
|
||||
start, save = {"cprofile": cprofile, "yappi": yappi_profiler, "memray": memray_allocations}[profiler](out)
|
||||
save = Once(save)
|
||||
if stop_file:
|
||||
# The watcher blocks before profiling starts, so it stays out of the profile.
|
||||
ready = threading.Event()
|
||||
threading.Thread(target=watch, args=(stop_waiter(stop_file), ready, save), daemon=True).start()
|
||||
threading.Thread(target=watch, args=(stop_waiter(stop_file), ready, save), name=WATCHER, daemon=True).start()
|
||||
ready.wait()
|
||||
start()
|
||||
try:
|
||||
run(target)
|
||||
try:
|
||||
run(target)
|
||||
finally:
|
||||
# Not after Stop: it ends a run that may be waiting for them.
|
||||
if not isinstance(sys.exc_info()[1], KeyboardInterrupt):
|
||||
finish_threads()
|
||||
finally:
|
||||
save()
|
||||
|
||||
|
||||
@@ -135,6 +135,7 @@ impl TreeBuilder {
|
||||
nodes,
|
||||
methods,
|
||||
calls: Vec::new(),
|
||||
threads: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Profiling Python under yappi with real interpreters: threads, thread pools, asyncio, exit
|
||||
//! codes, Stop, virtualenvs and `uv`. Tests that need yappi use `YAPPI_PYTHON` (an interpreter
|
||||
//! that imports it) or `python3` when that can; without one they return early. CI installs yappi.
|
||||
|
||||
use ide_profiler::{Profile, ProfileMode, ProfilePrepared, ProfileSpec, collect, prepare};
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn runs(python: &str, code: &str) -> bool {
|
||||
Command::new(python).args(["-c", code]).output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
/// An interpreter that imports yappi.
|
||||
fn yappi_python() -> Option<String> {
|
||||
let name =
|
||||
std::env::var("YAPPI_PYTHON").unwrap_or_else(|_| (if cfg!(windows) { "python" } else { "python3" }).into());
|
||||
runs(&name, "import yappi").then_some(name)
|
||||
}
|
||||
|
||||
fn config(python: &str, cwd: &Path, args: &[&str]) -> RunConfig {
|
||||
RunConfig {
|
||||
id: "y".into(),
|
||||
name: "yappi_run".into(),
|
||||
kind: "python".into(),
|
||||
command: python.into(),
|
||||
args: args.iter().map(|a| a.to_string()).collect(),
|
||||
cwd: Some(cwd.to_path_buf().into()),
|
||||
env: BTreeMap::new(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepared(c: &RunConfig, cwd: &Path, out: &Path, setting: &str) -> ProfilePrepared {
|
||||
prepare(cwd, c, out, ProfileMode::Cpu, setting)
|
||||
}
|
||||
|
||||
/// The yappi launch for `args` and where its profile goes.
|
||||
fn plan(python: &str, cwd: &Path, args: &[&str], out: &Path) -> (Command, ProfileSpec) {
|
||||
let ProfilePrepared::Ready { profiler, launch, spec } = prepared(&config(python, cwd, args), cwd, out, "auto")
|
||||
else {
|
||||
panic!("not ready");
|
||||
};
|
||||
assert_eq!(profiler, "yappi");
|
||||
let mut cmd = Command::new(&launch.command);
|
||||
cmd.args(&launch.args).current_dir(cwd).stdout(Stdio::piped());
|
||||
(cmd, spec)
|
||||
}
|
||||
|
||||
fn thread_spec(spec: &ProfileSpec, id: u32) -> ProfileSpec {
|
||||
let ProfileSpec::PythonRun { profiler, dir, root, .. } = spec else { panic!("not a Python run") };
|
||||
ProfileSpec::PythonRun { profiler: profiler.clone(), dir: dir.clone(), root: root.clone(), thread: Some(id) }
|
||||
}
|
||||
|
||||
fn method<'a>(p: &'a Profile, name: &str) -> Option<&'a ide_profiler::MethodStat> {
|
||||
p.methods.iter().find(|m| p.frames[m.frame as usize].name.contains(name))
|
||||
}
|
||||
|
||||
fn finish(mut child: std::process::Child) -> std::process::ExitStatus {
|
||||
for _ in 0..600 {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
child.kill().unwrap();
|
||||
panic!("the profiled run did not end");
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, text: &str) {
|
||||
std::fs::write(dir.join(name), text).unwrap();
|
||||
}
|
||||
|
||||
const THREADS: &str = "import threading, time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef in_thread():\n time.sleep(0.05)\n\ndef in_pool(i):\n time.sleep(0.02)\n\ndef main_work():\n sum(range(1000))\n\nt = threading.Thread(target=in_thread, name='worker')\nt.start()\nwith ThreadPoolExecutor(2) as pool:\n list(pool.map(in_pool, range(4)))\nt.join()\nmain_work()\n";
|
||||
|
||||
#[test]
|
||||
fn threads_and_thread_pools_are_listed_and_selectable() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(project.path(), "threads.py", THREADS);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["threads.py"], out.path());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let all = collect(&spec).unwrap();
|
||||
assert_eq!(all.profiler, "yappi");
|
||||
let names: Vec<&str> = all.threads.iter().map(|t| t.name.as_str()).collect();
|
||||
for expected in ["MainThread", "worker", "ThreadPoolExecutor-0_0"] {
|
||||
assert!(names.contains(&expected), "{names:?}");
|
||||
}
|
||||
// Merged: every thread's functions, with call counts.
|
||||
assert_eq!(method(&all, "in_pool").unwrap().calls, Some(4.0));
|
||||
assert!(method(&all, "in_thread").is_some() && method(&all, "main_work").is_some());
|
||||
// Busiest first.
|
||||
assert!(all.threads.windows(2).all(|w| w[0].total >= w[1].total));
|
||||
// One thread shows only its own functions.
|
||||
let worker = all.threads.iter().find(|t| t.name == "worker").unwrap();
|
||||
let w = collect(&thread_spec(&spec, worker.id)).unwrap();
|
||||
assert!(method(&w, "in_thread").is_some());
|
||||
assert!(method(&w, "in_pool").is_none() && method(&w, "main_work").is_none());
|
||||
assert_eq!(w.threads, all.threads, "the selector lists every thread whichever is shown");
|
||||
let main = all.threads.iter().find(|t| t.name == "MainThread").unwrap();
|
||||
let m = collect(&thread_spec(&spec, main.id)).unwrap();
|
||||
assert!(method(&m, "main_work").is_some() && method(&m, "in_thread").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_coroutines_time_includes_its_awaits() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
project.path(),
|
||||
"aio.py",
|
||||
"import asyncio\n\nasync def nap():\n await asyncio.sleep(0.1)\n\nasync def main():\n await asyncio.gather(nap(), nap())\n\nasyncio.run(main())\n",
|
||||
);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["aio.py"], out.path());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
let nap = method(&p, "nap").unwrap();
|
||||
assert_eq!(nap.calls, Some(2.0));
|
||||
// Two naps of 0.1 s, unit ms: cProfile would charge only the time between awaits.
|
||||
assert!(nap.total >= 180.0, "{}", nap.total);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_codes_c_code_and_modules_are_kept() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(
|
||||
&python,
|
||||
project.path(),
|
||||
&["-c", "import sys\ndef work(): return sum(range(9))\nwork()\nsys.exit(3)"],
|
||||
out.path(),
|
||||
);
|
||||
assert_eq!(finish(cmd.spawn().unwrap()).code(), Some(3));
|
||||
assert_eq!(method(&collect(&spec).unwrap(), "work (<string>:2)").unwrap().calls, Some(1.0));
|
||||
|
||||
write(project.path(), "app.py", "import sys\nprint(__name__, sys.argv[1:])\nsys.exit(4)\n");
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["-m", "app", "x", "--y"], out.path());
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
let mut printed = String::new();
|
||||
std::io::Read::read_to_string(&mut child.stdout.take().unwrap(), &mut printed).unwrap();
|
||||
assert_eq!(printed.trim(), "__main__ ['x', '--y']");
|
||||
assert_eq!(finish(child).code(), Some(4));
|
||||
collect(&spec).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uncaught_exception_still_leaves_a_profile() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) =
|
||||
plan(&python, project.path(), &["-c", "def boom():\n raise ValueError\nboom()"], out.path());
|
||||
cmd.stderr(Stdio::null());
|
||||
assert_eq!(finish(cmd.spawn().unwrap()).code(), Some(1));
|
||||
assert!(method(&collect(&spec).unwrap(), "boom").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_with_spaces_work() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let project = root.path().join("my project");
|
||||
let out = root.path().join("out dir");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
write(&project, "spaced script.py", "def spaced_fn():\n return 1\nspaced_fn()\n");
|
||||
let (mut cmd, spec) = plan(&python, &project, &["spaced script.py"], &out);
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
let f = method(&p, "spaced_fn").unwrap();
|
||||
assert_eq!(p.frames[f.frame as usize].file.as_deref(), Some(project.join("spaced script.py").as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursion_counts_total_and_primitive_calls_as_cprofile_does() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(project.path(), "rec.py", "def rec(n):\n return 0 if n == 0 else 1 + rec(n - 1)\nrec(50)\n");
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["rec.py"], out.path());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
let rec = method(&p, "rec").unwrap();
|
||||
assert_eq!((rec.calls, rec.primitive_calls), (Some(51.0), Some(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtins_are_named_like_cprofile_names_them() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
// A project file named like a built-in module must not be taken for its source.
|
||||
write(project.path(), "time", "");
|
||||
write(project.path(), "builtins", "");
|
||||
write(project.path(), "b.py", "import time\ntime.sleep(0.01)\nsorted([1])\nprint(len([]))\n");
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["b.py"], out.path());
|
||||
cmd.stdout(Stdio::null());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
for name in ["<built-in method time.sleep>", "<built-in function len>"] {
|
||||
let m = method(&p, name).unwrap_or_else(|| panic!("no {name}"));
|
||||
let frame = &p.frames[m.frame as usize];
|
||||
assert_eq!((frame.name.as_str(), frame.file.is_none()), (name, true), "{frame:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The interpreter joins non-daemon threads after the main thread returns; their work counts.
|
||||
#[test]
|
||||
fn work_of_threads_that_outlive_the_main_thread_is_profiled() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
project.path(),
|
||||
"late.py",
|
||||
"import threading, time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef late():\n time.sleep(0.3)\n sum(range(100))\n\nthreading.Thread(target=late, name='late').start()\nThreadPoolExecutor(1).submit(late)\n",
|
||||
);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["late.py"], out.path());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
// One call from the thread, one from the pool's worker.
|
||||
assert_eq!(method(&p, "<built-in function sum>").unwrap().calls, Some(2.0));
|
||||
let late = p.threads.iter().find(|t| t.name == "late").unwrap();
|
||||
assert!(late.total >= 0.25, "{late:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_short_threads_list_only_the_busiest() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
project.path(),
|
||||
"many.py",
|
||||
"import threading, time\n\ndef short():\n pass\n\ndef busy():\n time.sleep(0.2)\n\nb = threading.Thread(target=busy, name='busy')\nb.start()\nfor _ in range(300):\n t = threading.Thread(target=short)\n t.start()\n t.join()\nb.join()\n",
|
||||
);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["many.py"], out.path());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
assert_eq!(p.threads.len(), 64);
|
||||
assert!(p.threads.iter().any(|t| t.name == "busy"));
|
||||
assert_eq!(method(&p, "short").unwrap().calls, Some(300.0), "the merged profile has every thread");
|
||||
let files = std::fs::read_dir(out.path())
|
||||
.unwrap()
|
||||
.filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().starts_with("thread-"))
|
||||
.count();
|
||||
assert_eq!(files, 64);
|
||||
}
|
||||
|
||||
/// Child processes (multiprocessing) run as they would without the profiler; the exit code is kept.
|
||||
#[test]
|
||||
fn a_multiprocessing_pool_and_a_subprocess_exit_cleanly() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
project.path(),
|
||||
"mp.py",
|
||||
"import multiprocessing as mp, subprocess, sys\n\ndef square(x):\n return x * x\n\nif __name__ == '__main__':\n with mp.get_context('spawn').Pool(2) as pool:\n print(pool.map(square, [1, 2, 3]))\n sys.exit(subprocess.call([sys.executable, '-c', 'raise SystemExit(5)']))\n",
|
||||
);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["mp.py"], out.path());
|
||||
cmd.env("PYTHON_GIL", "1");
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
let mut printed = String::new();
|
||||
std::io::Read::read_to_string(&mut child.stdout.take().unwrap(), &mut printed).unwrap();
|
||||
assert_eq!(printed.trim(), "[1, 4, 9]");
|
||||
assert_eq!(finish(child).code(), Some(5));
|
||||
collect(&spec).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_damaged_thread_list_leaves_the_merged_profile() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(project.path(), "t.py", THREADS);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["t.py"], out.path());
|
||||
assert!(finish(cmd.spawn().unwrap()).success());
|
||||
std::fs::write(out.path().join("threads.json"), "{ not json").unwrap();
|
||||
assert!(collect(&spec).unwrap().threads.is_empty());
|
||||
std::fs::remove_file(out.path().join("threads.json")).unwrap();
|
||||
let p = collect(&spec).unwrap();
|
||||
assert!(p.threads.is_empty() && method(&p, "in_pool").is_some());
|
||||
// A thread whose file is gone is not listed; asking for it reports the missing file.
|
||||
std::fs::write(
|
||||
out.path().join("threads.json"),
|
||||
r#"[{"id":0,"name":"MainThread","total":1.0},{"id":99,"name":"gone","total":2.0}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(collect(&spec).unwrap().threads.iter().map(|t| t.id).collect::<Vec<_>>(), [0]);
|
||||
assert!(collect(&thread_spec(&spec, 99)).is_err());
|
||||
}
|
||||
|
||||
/// The first Stop (SIGINT) writes the snapshot, threads included.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_stopped_run_still_writes_its_profile_and_threads() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
project.path(),
|
||||
"loop.py",
|
||||
"import threading, time\ndef spin():\n while True:\n sum(range(1000))\nthreading.Thread(target=spin, daemon=True, name='spinner').start()\nprint('started', flush=True)\nwhile True:\n time.sleep(0.05)\n",
|
||||
);
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let (mut cmd, spec) = plan(&python, project.path(), &["loop.py"], out.path());
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(line.trim(), "started");
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
assert!(Command::new("kill").args(["-INT", &child.id().to_string()]).status().unwrap().success());
|
||||
finish(child);
|
||||
let p = collect(&spec).unwrap();
|
||||
let spinner = p.threads.iter().find(|t| t.name == "spinner").unwrap_or_else(|| panic!("{:?}", p.threads));
|
||||
// `spin` itself never returned; what it called did.
|
||||
assert!(method(&collect(&thread_spec(&spec, spinner.id)).unwrap(), "sum").is_some());
|
||||
}
|
||||
|
||||
/// What Stop does on Windows: the stop command opens the pipe (a FIFO elsewhere).
|
||||
#[test]
|
||||
fn the_stop_pipe_ends_the_run_and_keeps_its_profile() {
|
||||
let Some(python) = yappi_python() else { return };
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let code = "print('started', flush=True)\nwhile True:\n sum(range(1000))";
|
||||
let ProfilePrepared::Ready { mut launch, spec, .. } =
|
||||
prepared(&config(&python, project.path(), &["-c", code]), project.path(), out.path(), "yappi")
|
||||
else {
|
||||
panic!("not ready");
|
||||
};
|
||||
let fifo = out.path().join("stop");
|
||||
if launch.extras.stop_command.is_none() {
|
||||
let at = launch.args.iter().position(|a| a == "-c").unwrap();
|
||||
launch.args.splice(at..at, ["--stop".to_owned(), fifo.to_string_lossy().into_owned()]);
|
||||
}
|
||||
let mut cmd = Command::new(&launch.command);
|
||||
cmd.args(&launch.args).current_dir(project.path()).stdout(Stdio::piped());
|
||||
let mut child = cmd.spawn().unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(line.trim(), "started");
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
match &launch.extras.stop_command {
|
||||
#[cfg(windows)]
|
||||
Some(stop) => {
|
||||
use std::os::windows::process::CommandExt;
|
||||
assert!(Command::new("cmd").arg("/C").raw_arg(stop).status().unwrap().success());
|
||||
}
|
||||
_ => drop(std::fs::OpenOptions::new().write(true).open(&fifo).unwrap()),
|
||||
}
|
||||
assert!(!finish(child).success());
|
||||
let p = collect(&spec).unwrap();
|
||||
assert!(method(&p, "sum").is_some());
|
||||
// The watcher that waited for Stop stays out of the profile.
|
||||
assert!(method(&p, "watch").is_none() && method(&p, "stop_waiter").is_none());
|
||||
// A run that was stopped is one thread, not two with the watcher.
|
||||
assert_eq!(p.threads.len(), 1, "{:?}", p.threads);
|
||||
}
|
||||
|
||||
fn venv(base: &str, dir: &Path) -> String {
|
||||
assert!(Command::new(base).args(["-m", "venv"]).arg(dir).status().unwrap().success());
|
||||
let bin = dir.join(if cfg!(windows) { "Scripts" } else { "bin" });
|
||||
bin.join(if cfg!(windows) { "python.exe" } else { "python" }).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Automatic follows what the run's own interpreter imports; the setting overrides it.
|
||||
#[test]
|
||||
fn a_virtualenv_with_yappi_is_profiled_with_it_and_one_without_falls_back() {
|
||||
let Some(base) = yappi_python() else { return };
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let project = root.path().join("p");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let plain = venv(&base, &root.path().join("plain"));
|
||||
let profiler_of =
|
||||
|py: &str, setting: &str| match prepared(&config(py, &project, &["app.py"]), &project, out.path(), setting) {
|
||||
ProfilePrepared::Ready { profiler, .. } => profiler,
|
||||
ProfilePrepared::MissingTool { tool, install, .. } => {
|
||||
format!("missing {tool}: {}", install.map(|i| i.args.join(" ")).unwrap_or_default())
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
// A fresh virtualenv does not see the base interpreter's yappi.
|
||||
assert_eq!(profiler_of(&plain, "auto"), "cProfile");
|
||||
assert_eq!(profiler_of(&plain, "yappi"), "missing yappi: -m pip install yappi");
|
||||
assert!(Command::new(&plain).args(["-m", "pip", "install", "-q", "yappi"]).status().unwrap().success());
|
||||
assert_eq!(profiler_of(&plain, "auto"), "yappi");
|
||||
assert_eq!(profiler_of(&plain, "cprofile"), "cProfile");
|
||||
assert!(profiler_of(&plain, "py-spy").starts_with("missing py-spy"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_runs_are_probed_through_uv() {
|
||||
if !Command::new("uv").arg("--version").output().is_ok_and(|o| o.status.success()) {
|
||||
return;
|
||||
}
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
write(project.path(), "app.py", "def uv_fn():\n return 1\nuv_fn()\n");
|
||||
let out = tempfile::tempdir().unwrap();
|
||||
let c = config("uv", project.path(), &["run", "--no-project", "--with", "yappi", "python", "app.py"]);
|
||||
let ProfilePrepared::Ready { profiler, launch, spec } = prepared(&c, project.path(), out.path(), "auto") else {
|
||||
panic!("not ready");
|
||||
};
|
||||
assert_eq!(profiler, "yappi");
|
||||
let mut cmd = Command::new(&launch.command);
|
||||
assert!(cmd.args(&launch.args).current_dir(project.path()).status().unwrap().success());
|
||||
assert!(method(&collect(&spec).unwrap(), "uv_fn").is_some());
|
||||
}
|
||||
@@ -18,13 +18,14 @@ The program runs in the Run tool window as usual. If the profiler is missing, a
|
||||
| Runtime | Configurations | Profiler | Platforms |
|
||||
| --------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------ |
|
||||
| Node.js | `node`, `npx`, `tsx`, `ts-node` programs and npm, pnpm or yarn scripts | `node --cpu-prof` (set through `NODE_OPTIONS`, so every Node.js process of the run is profiled) | All |
|
||||
| Python | scripts, modules, pytest | `py-spy record` (subprocesses included) | All |
|
||||
| Python | scripts, modules, pytest | yappi, else `py-spy record`, else cProfile (see below) | All |
|
||||
| JVM | configurations that start `java`, such as Application and JAR Application | async-profiler agent (set through `JAVA_TOOL_OPTIONS`) | macOS, Linux |
|
||||
| Rust | `cargo run` | `perf record -g` | Linux |
|
||||
| Native programs | native configurations | `perf record -g` | Linux |
|
||||
|
||||
Setting up the profilers:
|
||||
|
||||
- **yappi**: when the run's interpreter can import it, Profile uses it (Settings › Python › Profiler › Automatic). It profiles every thread on the wall clock, so a coroutine's time includes its awaits, and the snapshot has a thread selector: **All threads merged** or one thread (the 64 busiest are listed). On the wall clock a thread that only waits counts as busy and threads overlap, so merged times can exceed the run's duration. Choosing yappi when it is missing offers `python -m pip install yappi`.
|
||||
- **py-spy**: the IDE looks next to the project's interpreter first, then on the search path. Without a package manager it offers `python -m pip install py-spy`.
|
||||
- **async-profiler**: unpack a release from [async-profiler releases](https://github.com/async-profiler/async-profiler/releases) and put its `bin/asprof` on the `PATH`, or set `ASYNC_PROFILER_HOME` to the unpacked folder. The IDE cannot install it for you.
|
||||
- **perf**: install your distribution's `linux-tools` / `linux-perf` package.
|
||||
|
||||
@@ -146,7 +146,7 @@ You can also create **Python** (a script or module), **pytest** and **Django tes
|
||||
| Run Context Configuration | `⌃⇧R` | `Ctrl+Shift+F10` |
|
||||
| Debug Context Configuration | `⌃⇧D` | none |
|
||||
|
||||
Run with Coverage uses coverage.py in the project interpreter, and Profile uses py-spy. When one is missing, the IDE says so and offers the command that installs it (for example `uv add --dev coverage` in a uv project). See [Coverage](/en/guide/coverage) and [Profiler](/en/guide/profiler).
|
||||
Run with Coverage uses coverage.py in the project interpreter, and Profile uses yappi, py-spy or the standard library's cProfile. When one is missing, the IDE says so and offers the command that installs it (for example `uv add --dev coverage` in a uv project). See [Coverage](/en/guide/coverage) and [Profiler](/en/guide/profiler).
|
||||
|
||||
Jupyter notebooks (`.ipynb`) run on a Python interpreter; see [Notebooks](/en/guide/notebook).
|
||||
|
||||
@@ -216,5 +216,5 @@ The **Celery** configuration type (**Run › Edit Configurations…**) runs a wo
|
||||
|
||||
- Only one type checker runs at a time. Ruff runs only in projects with a Ruff configuration.
|
||||
- Code intelligence and diagnostics come from the language server; the IDE has no Python analysis of its own.
|
||||
- Coverage and profiling need coverage.py and py-spy in your environment; the IDE does not keep its own copies of them.
|
||||
- Coverage and profiling need coverage.py (and yappi or py-spy for the better profilers) in your environment; the IDE does not keep its own copies of them.
|
||||
- Gutter run icons come from a line-based scan, so unusual test layouts may not get an icon. They can still run through a pytest configuration.
|
||||
@@ -18,13 +18,14 @@ description: "用采样分析器对运行配置做性能分析,并以火焰图
|
||||
| 运行时 | 配置 | 分析器 | 平台 |
|
||||
| -------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------ |
|
||||
| Node.js | `node`、`npx`、`tsx`、`ts-node` 程序,以及 npm、pnpm、yarn 脚本 | `node --cpu-prof`(通过 `NODE_OPTIONS` 设置,本次运行的所有 Node.js 进程都会被分析) | 全部 |
|
||||
| Python | 脚本、模块、pytest | `py-spy record`(包括子进程) | 全部 |
|
||||
| Python | 脚本、模块、pytest | yappi,否则 `py-spy record`,再否则 cProfile(见下) | 全部 |
|
||||
| JVM | 直接启动 `java` 的配置,例如 Application 和 JAR Application | async-profiler agent(通过 `JAVA_TOOL_OPTIONS` 设置) | macOS、Linux |
|
||||
| Rust | `cargo run` | `perf record -g` | Linux |
|
||||
| 原生程序 | native 配置 | `perf record -g` | Linux |
|
||||
|
||||
分析器的准备:
|
||||
|
||||
- **yappi**:运行所用的解释器能导入它时,Profile 使用它(设置 › Python › 性能分析器 › 自动)。它按墙钟时间分析所有线程,协程的时间包含其 await;快照带线程选择器:**所有线程合并**或单个线程(最多列出最忙的 64 个)。墙钟时间下,只在等待的线程也算忙,线程之间会重叠,所以合并后的时间可能超过运行时长。缺少 yappi 时选择它,会提供 `python -m pip install yappi`。
|
||||
- **py-spy**:IDE 先在项目解释器所在目录查找,再到搜索路径中查找。项目没有使用包管理器时,会提供 `python -m pip install py-spy`。
|
||||
- **async-profiler**:从 [async-profiler releases](https://github.com/async-profiler/async-profiler/releases) 下载并解压,把其中的 `bin/asprof` 加到 `PATH`,或者把 `ASYNC_PROFILER_HOME` 设为解压目录。IDE 无法替你安装。
|
||||
- **perf**:安装发行版的 `linux-tools` / `linux-perf` 软件包。
|
||||
|
||||
@@ -146,7 +146,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
| 运行上下文配置 | `⌃⇧R` | `Ctrl+Shift+F10` |
|
||||
| 调试上下文配置 | `⌃⇧D` | 无 |
|
||||
|
||||
**使用覆盖率运行** 使用项目解释器中的 coverage.py,**性能分析** 使用 py-spy。缺少时 IDE 会提示,并给出安装命令(例如 uv 项目中的 `uv add --dev coverage`)。详见[覆盖率](/zh/guide/coverage)和[性能分析](/zh/guide/profiler)。
|
||||
**使用覆盖率运行** 使用项目解释器中的 coverage.py,**性能分析** 使用 yappi、py-spy 或标准库的 cProfile。缺少时 IDE 会提示,并给出安装命令(例如 uv 项目中的 `uv add --dev coverage`)。详见[覆盖率](/zh/guide/coverage)和[性能分析](/zh/guide/profiler)。
|
||||
|
||||
Jupyter Notebook(`.ipynb`)在 Python 解释器上运行,见 [Notebook](/zh/guide/notebook)。
|
||||
|
||||
@@ -216,5 +216,5 @@ Django 项目(上层目录有 `manage.py`)中 `templates` 目录里的 HTML
|
||||
|
||||
- 同一时间只运行一个类型检查器。Ruff 只在有 Ruff 配置的项目中运行。
|
||||
- 代码智能和诊断都来自语言服务器,IDE 自身不做 Python 分析。
|
||||
- 覆盖率和性能分析需要你的环境中装有 coverage.py 和 py-spy,IDE 不自带这两个工具。
|
||||
- 覆盖率和性能分析需要你的环境中装有 coverage.py(性能分析可再装 yappi 或 py-spy),IDE 不自带这两个工具。
|
||||
- 左侧栏的运行图标基于逐行扫描,不常见的测试写法可能没有图标,但仍可以通过 pytest 配置运行。
|
||||
+17
-5
@@ -15050,7 +15050,7 @@ export type ProcessMemory = {
|
||||
};
|
||||
|
||||
export type Profile = {
|
||||
/** `node --cpu-prof`, `py-spy`, `async-profiler`, `perf`. */
|
||||
/** `node --cpu-prof`, `yappi`, `cProfile`, `py-spy`, `async-profiler`, `perf`. */
|
||||
profiler: string,
|
||||
/** `ms` (time-weighted), `samples` (sample or live-object counts) or `bytes` (allocated). */
|
||||
unit: string,
|
||||
@@ -15066,6 +15066,8 @@ export type Profile = {
|
||||
* from them, so below the first level it is an estimate. Empty for sampled profiles.
|
||||
*/
|
||||
calls: CallEdge[],
|
||||
/** The threads of a yappi run, busiest first; empty when the profiler does not tell them apart. */
|
||||
threads: ProfileThread[],
|
||||
};
|
||||
|
||||
export type ProfileFrame = {
|
||||
@@ -15125,9 +15127,10 @@ export type ProfileSpec =
|
||||
{ kind: "snapshotFile"; path: IpcPath; root: IpcPath | null } |
|
||||
/**
|
||||
* What `python_profile.py` wrote in `dir` for a profiled Python run: `profile.pstats`.
|
||||
* Relative source files resolve against `root`.
|
||||
* Relative source files resolve against `root`. `thread`: a yappi run's thread to show
|
||||
* (`Profile::threads`), else all threads merged.
|
||||
*/
|
||||
{ kind: "pythonRun"; profiler: string; dir: IpcPath; root: IpcPath } |
|
||||
{ kind: "pythonRun"; profiler: string; dir: IpcPath; root: IpcPath; thread: number | null } |
|
||||
/**
|
||||
* The `memray.bin` capture `python_profile.py` wrote in `dir`, read with
|
||||
* `<python> -m memray transform csv`: what was allocated at the memory peak.
|
||||
@@ -15143,6 +15146,14 @@ export type ProfileSpec =
|
||||
/** `perf script -i <data>` output. */
|
||||
{ kind: "perf"; perf: string; data: IpcPath; cwd: IpcPath; env: { [key in string]: string } };
|
||||
|
||||
/** A thread of a yappi run. Its own profile is `collect`ed with the spec's `thread` set to `id`. */
|
||||
export type ProfileThread = {
|
||||
id: number,
|
||||
name: string,
|
||||
/** Seconds the thread ran (wall clock). */
|
||||
total: number | null,
|
||||
};
|
||||
|
||||
/** A command line that installs a missing profiler. */
|
||||
export type ProfilerInstall = {
|
||||
command: string,
|
||||
@@ -15611,8 +15622,9 @@ export type PythonSettings = {
|
||||
*/
|
||||
testRunner?: string,
|
||||
/**
|
||||
* What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
* is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
* What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the
|
||||
* interpreter can import it, else py-spy where it is installed and samples without root, else
|
||||
* cProfile), `cprofile`, `py-spy` or `yappi`.
|
||||
*/
|
||||
profiler?: string,
|
||||
/**
|
||||
|
||||
@@ -26,6 +26,7 @@ function profile(mode: ProfileMode, total: number): Profile {
|
||||
],
|
||||
methods: [{ frame: 2, selfWeight: total, total, calls: null, primitiveCalls: null }],
|
||||
calls: [],
|
||||
threads: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -169,4 +170,48 @@ describe("ProfilerView", () => {
|
||||
render(<ProfilerView />);
|
||||
expect(screen.queryByRole("columnheader", { name: "Calls" })).toBeNull();
|
||||
});
|
||||
|
||||
it("lists the threads of a yappi run, merged first", async () => {
|
||||
const cpu = profile("cpu", 100);
|
||||
const threads = [
|
||||
{ id: 0, name: "MainThread", total: 0.1 },
|
||||
{ id: 1, name: "worker", total: 0.05 },
|
||||
];
|
||||
const spec = {
|
||||
kind: "pythonRun" as const,
|
||||
profiler: "yappi",
|
||||
dir: "/o",
|
||||
root: "/p",
|
||||
thread: null,
|
||||
};
|
||||
addSnapshot("run", { ...cpu, profiler: "yappi", threads }, null, undefined, spec);
|
||||
render(<ProfilerView />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Thread" }));
|
||||
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual([
|
||||
"All threads merged",
|
||||
"MainThread (100 ms)",
|
||||
"worker (50.0 ms)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers no thread selector for a single thread", () => {
|
||||
addSnapshot(
|
||||
"run",
|
||||
{
|
||||
...profile("cpu", 100),
|
||||
threads: [{ id: 0, name: "MainThread", total: 0.1 }],
|
||||
},
|
||||
null,
|
||||
undefined,
|
||||
{
|
||||
kind: "pythonRun",
|
||||
profiler: "yappi",
|
||||
dir: "/o",
|
||||
root: "/p",
|
||||
thread: null,
|
||||
},
|
||||
);
|
||||
render(<ProfilerView />);
|
||||
expect(screen.queryByRole("button", { name: "Thread" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,9 +5,9 @@
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { Profile } from "@/platform/ipc";
|
||||
import { Button, EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { call, commands, type Profile } from "@/platform/ipc";
|
||||
import { Button, EmptyState, Icon, IconButton, Input, Select, Tabs, Tree, T } from "@/ui";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import {
|
||||
callSites,
|
||||
@@ -21,7 +21,14 @@ import {
|
||||
share,
|
||||
type CallSite,
|
||||
} from "./model";
|
||||
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
|
||||
import {
|
||||
activeSnapshot,
|
||||
closeSnapshot,
|
||||
setSnapshotThread,
|
||||
useProfiler,
|
||||
type ProfilerTab,
|
||||
type Snapshot,
|
||||
} from "./store";
|
||||
import styles from "./Profiler.module.css";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
|
||||
@@ -397,6 +404,48 @@ function CallSiteList({
|
||||
);
|
||||
}
|
||||
|
||||
let latestThread = 0;
|
||||
|
||||
/** "All threads merged" and each thread of a yappi run, busiest first. */
|
||||
function ThreadSelect({ snapshot }: { snapshot: Snapshot }) {
|
||||
const tx = useTx();
|
||||
const { spec, profile } = snapshot;
|
||||
if (!spec || spec.kind !== "pythonRun" || profile.threads.length < 2) return null;
|
||||
const options = [
|
||||
{ value: "all", label: tx("All threads merged") },
|
||||
...profile.threads.map((t) => ({
|
||||
value: String(t.id),
|
||||
label: `${t.name} (${formatWeight((t.total ?? 0) * 1000, "ms")})`,
|
||||
})),
|
||||
];
|
||||
const select = (v: string) => {
|
||||
const thread = v === "all" ? null : Number(v);
|
||||
const mine = ++latestThread;
|
||||
void call(commands.profilerCollect({ ...spec, thread }))
|
||||
// Only the last pick counts when the reads finish out of order.
|
||||
.then((p) => mine === latestThread && setSnapshotThread(snapshot.id, p, thread))
|
||||
.catch((e) => {
|
||||
if (mine !== latestThread) return;
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
key: "profiler-thread",
|
||||
title: tx("Couldn't show that thread"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
});
|
||||
};
|
||||
return (
|
||||
<Select
|
||||
aria-label={tx("Thread")}
|
||||
variant="ghost"
|
||||
value={snapshot.thread == null ? "all" : String(snapshot.thread)}
|
||||
options={options}
|
||||
onChange={select}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProfilerView() {
|
||||
const tx = useTx();
|
||||
const snapshot = useProfiler((s) => activeSnapshot(s));
|
||||
@@ -434,6 +483,7 @@ export function ProfilerView() {
|
||||
{ id: "methods", label: "Method List" },
|
||||
]}
|
||||
/>
|
||||
<ThreadSelect snapshot={snapshot} />
|
||||
<span className={styles.muted}>{profileSummary(profile, tx)}</span>
|
||||
{tab !== "tree" && (
|
||||
<Input
|
||||
|
||||
@@ -91,7 +91,13 @@ async function prepare(config: RunConfig, mode: ProfileMode): Promise<ExecutorLa
|
||||
void (async () => {
|
||||
try {
|
||||
const profile = await call(commands.profilerCollect(spec));
|
||||
addSnapshot(config.name, profile, mode === "liveObjects" ? liveNotice(stopped) : treeNotice(profile));
|
||||
addSnapshot(
|
||||
config.name,
|
||||
profile,
|
||||
mode === "liveObjects" ? liveNotice(stopped) : treeNotice(profile),
|
||||
undefined,
|
||||
spec,
|
||||
);
|
||||
try {
|
||||
toolWindowService().show("profiler", true);
|
||||
} catch {
|
||||
|
||||
@@ -198,8 +198,12 @@ export function colorSlot(name: string): number {
|
||||
const ESTIMATED_TREE =
|
||||
"cProfile records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact.";
|
||||
|
||||
/** The notice of a call-graph profile (cProfile): its call edges are exact, its call tree an estimate. */
|
||||
const YAPPI_NOTICE =
|
||||
"yappi records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact. Times are wall clock: a thread that waits counts as busy, and threads and coroutines overlap, so merged times can exceed the run's duration.";
|
||||
|
||||
/** The notice of a call-graph profile (cProfile, yappi): its call edges are exact, its call tree an estimate. */
|
||||
export function treeNotice(profile: Profile): string | null {
|
||||
if (profile.profiler === "yappi") return YAPPI_NOTICE;
|
||||
return profile.calls.length ? ESTIMATED_TREE : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ const profile: Profile = {
|
||||
],
|
||||
methods: [],
|
||||
calls: [],
|
||||
threads: [],
|
||||
};
|
||||
|
||||
function cfg(command: string, args: string[], kind = "shell"): RunConfig {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Profiler snapshots of this project window (the last few stay open as tabs). */
|
||||
import { create } from "zustand";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { Profile } from "@/platform/ipc";
|
||||
import type { Profile, ProfileSpec } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
export const MAX_SNAPSHOTS = 5;
|
||||
@@ -16,6 +16,10 @@ export interface Snapshot {
|
||||
notice: string | null;
|
||||
/** The `.cpuprofile` it was opened from; opening the file again replaces it. */
|
||||
path?: string;
|
||||
/** How a run's profile is read again, to show one thread of it (yappi). */
|
||||
spec?: ProfileSpec;
|
||||
/** The thread shown: its id in `profile.threads`, else all threads merged. */
|
||||
thread?: number | null;
|
||||
}
|
||||
|
||||
export type ProfilerTab = "flame" | "tree" | "methods";
|
||||
@@ -33,7 +37,13 @@ export const useProfiler = create<ProfilerState>(() => ({ snapshots: [], activeI
|
||||
let seq = 0;
|
||||
|
||||
/** Adds a snapshot in front; the oldest beyond {@link MAX_SNAPSHOTS} close, with a notification. */
|
||||
export function addSnapshot(name: string, profile: Profile, notice: string | null = null, path?: string): Snapshot {
|
||||
export function addSnapshot(
|
||||
name: string,
|
||||
profile: Profile,
|
||||
notice: string | null = null,
|
||||
path?: string,
|
||||
spec?: ProfileSpec,
|
||||
): Snapshot {
|
||||
const prev = useProfiler.getState().snapshots;
|
||||
const same = path === undefined ? undefined : prev.find((x) => x.path === path);
|
||||
const snapshot: Snapshot = {
|
||||
@@ -43,6 +53,7 @@ export function addSnapshot(name: string, profile: Profile, notice: string | nul
|
||||
profile,
|
||||
notice,
|
||||
...(path !== undefined && { path }),
|
||||
...(spec !== undefined && { spec }),
|
||||
};
|
||||
const rest = prev.filter((x) => x !== same);
|
||||
const dropped = rest.slice(MAX_SNAPSHOTS - 1);
|
||||
@@ -60,6 +71,11 @@ export function addSnapshot(name: string, profile: Profile, notice: string | nul
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Shows `profile` (another thread's) in snapshot `id`. */
|
||||
export function setSnapshotThread(id: string, profile: Profile, thread: number | null) {
|
||||
useProfiler.setState((s) => ({ snapshots: s.snapshots.map((x) => (x.id === id ? { ...x, profile, thread } : x)) }));
|
||||
}
|
||||
|
||||
export function activeSnapshot(s: ProfilerState = useProfiler.getState()): Snapshot | null {
|
||||
return s.snapshots.find((x) => x.id === s.activeId) ?? null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { Profile } from "@/platform/ipc";
|
||||
|
||||
const ipc = vi.hoisted(() => ({ collect: vi.fn(), notify: vi.fn() }));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/ipc")>()),
|
||||
call: async <T,>(p: Promise<{ status: "ok"; data: T } | { status: "error"; error: unknown }>) => {
|
||||
const r = await p;
|
||||
if (r.status === "error") throw new Error(String(r.error));
|
||||
return r.data;
|
||||
},
|
||||
commands: { profilerCollect: ipc.collect },
|
||||
}));
|
||||
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: ipc.notify }),
|
||||
}));
|
||||
|
||||
import { ProfilerView } from "./ProfilerView";
|
||||
import { addSnapshot, resetProfiler, useProfiler } from "./store";
|
||||
|
||||
const threads = [
|
||||
{ id: 0, name: "MainThread", total: 0.1 },
|
||||
{ id: 1, name: "worker", total: 0.05 },
|
||||
{ id: 2, name: "pool", total: 0.02 },
|
||||
];
|
||||
|
||||
function profile(method: string): Profile {
|
||||
return {
|
||||
profiler: "yappi",
|
||||
unit: "ms",
|
||||
mode: "cpu",
|
||||
total: 10,
|
||||
frames: [
|
||||
{ name: "all", file: null, line: null, kind: "code" },
|
||||
{ name: method, file: null, line: null, kind: "code" },
|
||||
],
|
||||
nodes: [
|
||||
{ frame: 0, total: 10, selfWeight: 0, children: [1] },
|
||||
{ frame: 1, total: 10, selfWeight: 10, children: [] },
|
||||
],
|
||||
methods: [{ frame: 1, selfWeight: 10, total: 10, calls: 1, primitiveCalls: 1 }],
|
||||
calls: [],
|
||||
threads,
|
||||
};
|
||||
}
|
||||
|
||||
const spec = { kind: "pythonRun" as const, profiler: "yappi", dir: "/o", root: "/p", thread: null };
|
||||
const ok = (data: Profile) => ({ status: "ok", data });
|
||||
|
||||
function pick(label: string) {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Thread" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: label }));
|
||||
}
|
||||
|
||||
describe("thread selector", () => {
|
||||
beforeEach(() => {
|
||||
resetProfiler();
|
||||
useProfiler.setState({ tab: "methods" });
|
||||
ipc.collect.mockReset();
|
||||
ipc.notify.mockReset();
|
||||
addSnapshot("run", profile("merged_fn"), null, undefined, spec);
|
||||
});
|
||||
afterEach(() => resetProfiler());
|
||||
|
||||
it("reads the picked thread's profile and goes back to all threads", async () => {
|
||||
ipc.collect.mockImplementation(async (s: { thread: number | null }) =>
|
||||
ok(profile(s.thread === 1 ? "worker_fn" : "merged_fn")),
|
||||
);
|
||||
render(<ProfilerView />);
|
||||
pick("worker (50.0 ms)");
|
||||
await waitFor(() => expect(screen.getByText("worker_fn")).toBeInTheDocument());
|
||||
expect(ipc.collect).toHaveBeenLastCalledWith({ ...spec, thread: 1 });
|
||||
pick("All threads merged");
|
||||
await waitFor(() => expect(screen.getByText("merged_fn")).toBeInTheDocument());
|
||||
expect(ipc.collect).toHaveBeenLastCalledWith({ ...spec, thread: null });
|
||||
});
|
||||
|
||||
it("says so when a thread's profile cannot be read, and keeps the one shown", async () => {
|
||||
ipc.collect.mockResolvedValue({ status: "error", error: "thread-1.pstats is missing" });
|
||||
render(<ProfilerView />);
|
||||
pick("worker (50.0 ms)");
|
||||
await waitFor(() => expect(ipc.notify).toHaveBeenCalled());
|
||||
expect(ipc.notify.mock.calls[0]![0]).toMatchObject({ level: "error", body: "thread-1.pstats is missing" });
|
||||
expect(screen.getByText("merged_fn")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the last pick when the reads finish out of order", async () => {
|
||||
const slow: Array<() => void> = [];
|
||||
ipc.collect.mockImplementation(
|
||||
(s: { thread: number | null }) =>
|
||||
new Promise((resolve) => {
|
||||
const done = () => resolve(ok(profile(s.thread === 1 ? "worker_fn" : "pool_fn")));
|
||||
if (s.thread === 1) slow.push(done);
|
||||
else done();
|
||||
}),
|
||||
);
|
||||
render(<ProfilerView />);
|
||||
pick("worker (50.0 ms)");
|
||||
pick("pool (20.0 ms)");
|
||||
await waitFor(() => expect(screen.getByText("pool_fn")).toBeInTheDocument());
|
||||
slow.forEach((f) => f());
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(screen.getByText("pool_fn")).toBeInTheDocument();
|
||||
expect(screen.queryByText("worker_fn")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ const PROFILERS = [
|
||||
{ value: "auto", label: "Automatic" },
|
||||
{ value: "cprofile", label: "cProfile" },
|
||||
{ value: "py-spy", label: "py-spy" },
|
||||
{ value: "yappi", label: "yappi" },
|
||||
] as const;
|
||||
|
||||
export function PythonProfilerPage() {
|
||||
@@ -16,7 +17,7 @@ export function PythonProfilerPage() {
|
||||
<SettingSelect
|
||||
k="languages.python.profiler"
|
||||
label="Profiler"
|
||||
hint="Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library."
|
||||
hint="Automatic uses yappi (every thread and coroutine) when the interpreter has it installed, else py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library."
|
||||
options={PROFILERS}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
@@ -317,7 +317,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [
|
||||
title: "Profiler",
|
||||
group: LANGUAGES_GROUP,
|
||||
order: 403.27,
|
||||
keywords: ["profiler", "profile", "cprofile", "py-spy", "performance"],
|
||||
keywords: ["profiler", "profile", "cprofile", "py-spy", "yappi", "performance"],
|
||||
component: PythonProfilerPage,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -378,6 +378,7 @@ describe("catalogs", () => {
|
||||
// Python profilers (Settings › Python › Profiler).
|
||||
"cProfile",
|
||||
"py-spy",
|
||||
"yappi",
|
||||
// Python unittest: the runner's name and a dotted module placeholder.
|
||||
"unittest",
|
||||
"tests.test_models",
|
||||
|
||||
@@ -327,7 +327,7 @@ export type FolderListKey =
|
||||
export const PYTHON_TEST_RUNNERS = ["auto", "pytest", "unittest"] as const;
|
||||
export type PythonTestRunner = (typeof PYTHON_TEST_RUNNERS)[number];
|
||||
|
||||
export const PYTHON_PROFILERS = ["auto", "cprofile", "py-spy"] as const;
|
||||
export const PYTHON_PROFILERS = ["auto", "cprofile", "py-spy", "yappi"] as const;
|
||||
export type PythonProfiler = (typeof PYTHON_PROFILERS)[number];
|
||||
|
||||
export const DEFAULT_LANGUAGES: LanguagesValid = {
|
||||
|
||||
@@ -4687,7 +4687,11 @@
|
||||
"Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window.": "Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window.",
|
||||
"cProfile": "cProfile",
|
||||
"py-spy": "py-spy",
|
||||
"Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.",
|
||||
"yappi": "yappi",
|
||||
"yappi records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact. Times are wall clock: a thread that waits counts as busy, and threads and coroutines overlap, so merged times can exceed the run's duration.": "yappi records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact. Times are wall clock: a thread that waits counts as busy, and threads and coroutines overlap, so merged times can exceed the run's duration.",
|
||||
"Couldn't show that thread": "Couldn't show that thread",
|
||||
"All threads merged": "All threads merged",
|
||||
"Automatic uses yappi (every thread and coroutine) when the interpreter has it installed, else py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "Automatic uses yappi (every thread and coroutine) when the interpreter has it installed, else py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.",
|
||||
"No safe lint fixes to apply": "No safe lint fixes to apply",
|
||||
"Run manage.py Task…": "Run manage.py Task…",
|
||||
"No manage.py in this project": "No manage.py in this project",
|
||||
|
||||
@@ -11385,7 +11385,11 @@
|
||||
"Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window.": "运行、调试会话和 Python 控制台的 matplotlib 图形会发送到“绘图”工具窗口,除非运行自行设置了 MPLBACKEND;matplotlibrc 中设置的后端会被覆盖。关闭后,图形在 matplotlib 自己的窗口中打开。",
|
||||
"cProfile": "cProfile",
|
||||
"py-spy": "py-spy",
|
||||
"Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "自动:已安装 py-spy 且无需 root 即可采样时(macOS 除外)使用 py-spy,否则使用标准库的 cProfile。",
|
||||
"yappi": "yappi",
|
||||
"yappi records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact. Times are wall clock: a thread that waits counts as busy, and threads and coroutines overlap, so merged times can exceed the run's duration.": "yappi 只记录调用方和被调用方,不记录完整调用栈:火焰图和调用树由它们估算,方法列表是精确的。时间为墙钟时间:等待中的线程也算忙,线程和协程之间会重叠,所以合并后的时间可能超过运行时长。",
|
||||
"Couldn't show that thread": "无法显示该线程",
|
||||
"All threads merged": "所有线程合并",
|
||||
"Automatic uses yappi (every thread and coroutine) when the interpreter has it installed, else py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "自动:解释器已安装 yappi 时使用 yappi(覆盖所有线程和协程);否则已安装 py-spy 且无需 root 即可采样时使用 py-spy(macOS 除外);再否则使用标准库的 cProfile。",
|
||||
"No safe lint fixes to apply": "没有可应用的安全 lint 修复",
|
||||
"Run manage.py Task…": "运行 manage.py 任务…",
|
||||
"No manage.py in this project": "此项目中没有 manage.py",
|
||||
|
||||
Reference in new issue
Заблокувати користувача