дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Open Snapshot… and Open in Profiler accept pstats files written by cProfile / profile (and yappi's pstat export), told apart from a V8 .cpuprofile by content. The marshal'd pstats dict is read in Rust without a Python interpreter. The method list shows exact own time, total time and call counts (total/primitive for recursion); selecting a method lists its callers and callees, exact for cProfile and summed from the call tree for sampled profiles. The flame graph and call tree are rebuilt from the caller/callee totals, sharing each function's time among its callers in proportion, with a notice that they are estimated; recursion is not unfolded, roots are the strongly connected components of the call graph, and the tree is bounded in share and node count. Recorded files resolve against the project root, then the snapshot's folder, each file looked up once. Closes #6367 Co-authored-by: wildcatDownstairs <[email protected]>
460 рядки
17 KiB
TypeScript
460 рядки
17 KiB
TypeScript
/**
|
|
* Profiler tool window: one tab per snapshot, and per snapshot a flame graph
|
|
* (click to zoom, search highlights), the call tree (top-down) and the method
|
|
* list (self / total). Double-click opens a frame's source when known.
|
|
*/
|
|
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 { executeAction } from "@/platform/actions";
|
|
import {
|
|
callSites,
|
|
colorSlot,
|
|
flameLayout,
|
|
flameStep,
|
|
formatCalls,
|
|
formatWeight,
|
|
frameLocation,
|
|
matchingFrames,
|
|
share,
|
|
type CallSite,
|
|
} from "./model";
|
|
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
|
|
import styles from "./Profiler.module.css";
|
|
import { useTx } from "@/platform/i18n";
|
|
|
|
const ROW = 18;
|
|
|
|
/** Names the allocation modes for the snapshot tabs; CPU profiles keep the plain run name. */
|
|
function useModeLabel(): (profile: Profile) => string | null {
|
|
const tx = useTx();
|
|
return (profile) =>
|
|
profile.mode === "allocations" ? tx("Allocations") : profile.mode === "liveObjects" ? tx("Live Objects") : null;
|
|
}
|
|
|
|
/** Faint mark after the name of a frame that is an allocated type rather than code. */
|
|
function TypeMark({ profile, frame }: { profile: Profile; frame: number }) {
|
|
if (profile.frames[frame]!.kind !== "allocatedType") return null;
|
|
return (
|
|
<span className={styles.typeMark}>
|
|
<T>allocated</T>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/** `async-profiler · 612.4 MB allocated`; what the weight counts depends on the mode. */
|
|
function profileSummary(profile: Profile, tx: ReturnType<typeof useTx>): string {
|
|
const total = profile.total ?? 0;
|
|
if (profile.mode === "allocations") {
|
|
const size = formatWeight(total, profile.unit);
|
|
return `${profile.profiler} · ${tx`${size} allocated`}`;
|
|
}
|
|
if (profile.mode === "liveObjects") {
|
|
const count = Math.round(total);
|
|
const live = count === 1 ? tx("1 live sample (≈ 512 KB)") : tx`${count} live samples (≈ 512 KB each)`;
|
|
return `${profile.profiler} · ${live}`;
|
|
}
|
|
return `${profile.profiler} · ${formatWeight(total, profile.unit)}`;
|
|
}
|
|
|
|
function openFrame(profile: Profile, frame: number) {
|
|
const f = profile.frames[frame];
|
|
if (!f?.file) return;
|
|
void editorService().openFile(
|
|
f.file,
|
|
f.line !== null ? { selection: { line: f.line, col: 0 }, focus: true } : { focus: true },
|
|
);
|
|
}
|
|
|
|
export function ProfilerHeaderActions() {
|
|
return <IconButton icon="open" action="profiler.openSnapshot" size="small" />;
|
|
}
|
|
|
|
export function ProfilerTabs() {
|
|
const snapshots = useProfiler((s) => s.snapshots);
|
|
const activeId = useProfiler((s) => s.activeId);
|
|
const modeLabel = useModeLabel();
|
|
if (!snapshots.length) return null;
|
|
return (
|
|
<Tabs
|
|
variant="compact"
|
|
aria-label="Profiler snapshots"
|
|
className={styles.tabs}
|
|
activeId={activeId}
|
|
onSelect={(id) => useProfiler.setState({ activeId: id })}
|
|
onClose={closeSnapshot}
|
|
items={snapshots.map((s) => {
|
|
const mode = modeLabel(s.profile);
|
|
return {
|
|
id: s.id,
|
|
label: mode ? `${s.name} · ${mode}` : s.name,
|
|
verbatim: true,
|
|
closable: true,
|
|
tooltip: `${s.profile.profiler}, ${mode ? `${mode}, ` : ""}${new Date(s.createdAt).toLocaleTimeString()}`,
|
|
};
|
|
})}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
|
const tx = useTx();
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
const [width, setWidth] = useState(0);
|
|
const [focus, setFocus] = useState(0);
|
|
useLayoutEffect(() => {
|
|
const el = ref.current;
|
|
if (!el) return;
|
|
const ro = new ResizeObserver(() => setWidth(el.clientWidth));
|
|
ro.observe(el);
|
|
setWidth(el.clientWidth);
|
|
return () => ro.disconnect();
|
|
}, []);
|
|
const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]);
|
|
// The frame the keyboard is on: arrows move it, Enter zooms into it, F4 opens its source.
|
|
const [current, setCurrent] = useState(0);
|
|
const shown = layout.rects.some((r) => r.node === current) ? current : focus;
|
|
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
|
const moves: Record<string, Parameters<typeof flameStep>[2]> = {
|
|
ArrowUp: "deeper",
|
|
ArrowDown: "shallower",
|
|
ArrowLeft: "previous",
|
|
ArrowRight: "next",
|
|
};
|
|
const move = moves[e.key];
|
|
if (move) setCurrent(flameStep(layout.rects, shown, move));
|
|
else if (e.key === "Enter") setFocus(shown);
|
|
else if (e.key === "Escape" && focus !== 0) setFocus(0);
|
|
else if (e.key === "F4") openFrame(profile, profile.nodes[shown]!.frame);
|
|
else return;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
};
|
|
useEffect(() => {
|
|
ref.current?.querySelector(`[data-node="${shown}"]`)?.scrollIntoView?.({ block: "nearest" });
|
|
}, [shown]);
|
|
const matches = useMemo(() => matchingFrames(profile, query), [profile, query]);
|
|
const unit = profile.unit;
|
|
const total = profile.total ?? 0;
|
|
|
|
return (
|
|
<div className={styles.flamePane}>
|
|
{focus !== 0 && (
|
|
<div className={styles.flameBar}>
|
|
<IconButton icon="close" size="small" title="Reset Zoom" onClick={() => setFocus(0)} />
|
|
<span className={styles.muted}>{tx`Zoomed into ${profile.frames[profile.nodes[focus]!.frame]!.name}`}</span>
|
|
</div>
|
|
)}
|
|
<div className={styles.flameScroll} ref={ref}>
|
|
<div
|
|
className={styles.flame}
|
|
style={{ height: layout.depth * ROW }}
|
|
role="tree"
|
|
aria-label={tx("Flame graph")}
|
|
tabIndex={0}
|
|
aria-activedescendant={`flame-frame-${shown}`}
|
|
onKeyDown={onKeyDown}
|
|
>
|
|
{width > 0 &&
|
|
layout.rects.map((r) => {
|
|
const node = profile.nodes[r.node]!;
|
|
const frame = profile.frames[node.frame]!;
|
|
const w = r.width * width;
|
|
const location = frameLocation(profile, node.frame);
|
|
const label = r.node === 0 ? `all (${formatWeight(total, unit)})` : frame.name;
|
|
return (
|
|
<div
|
|
key={r.node}
|
|
id={`flame-frame-${r.node}`}
|
|
data-node={r.node}
|
|
role="treeitem"
|
|
aria-label={label}
|
|
aria-selected={r.node === shown}
|
|
className={clsx(
|
|
styles.frame,
|
|
r.node === shown && styles.current,
|
|
styles[`c${colorSlot(frame.name)}`],
|
|
frame.kind === "allocatedType" && styles.typeFrame,
|
|
matches && (matches.has(node.frame) ? styles.match : styles.dim),
|
|
)}
|
|
style={{ left: r.x * width, width: Math.max(w - 1, 1), bottom: r.depth * ROW }}
|
|
title={`${frame.kind === "allocatedType" ? `${tx("Allocated type")}\n` : ""}${frame.name}${location ? ` (${location})` : ""}\nTotal: ${formatWeight(node.total ?? 0, unit)} (${share(node.total ?? 0, total)})\nSelf: ${formatWeight(node.selfWeight ?? 0, unit)}`}
|
|
onClick={() => {
|
|
setCurrent(r.node);
|
|
setFocus(r.node);
|
|
}}
|
|
onDoubleClick={() => openFrame(profile, node.frame)}
|
|
>
|
|
{w > 28 && <span className={styles.frameText}>{label}</span>}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function CallTree({ profile }: { profile: Profile }) {
|
|
const total = profile.total ?? 0;
|
|
const roots = useMemo(() => profile.nodes[0]?.children ?? [], [profile]);
|
|
const [expanded, setExpanded] = useState<Set<string> | null>(null);
|
|
// The heaviest path starts expanded (IDEA expands the hottest call chain).
|
|
const initial = useMemo(() => {
|
|
const set = new Set<string>();
|
|
let cur = roots[0];
|
|
for (let i = 0; cur !== undefined && i < 30; i++) {
|
|
set.add(String(cur));
|
|
cur = profile.nodes[cur]!.children[0];
|
|
}
|
|
return set;
|
|
}, [profile, roots]);
|
|
return (
|
|
<Tree<number>
|
|
aria-label="Call tree"
|
|
className={styles.tree}
|
|
roots={roots}
|
|
getKey={(n) => String(n)}
|
|
getLabel={(n) => profile.frames[profile.nodes[n]!.frame]!.name}
|
|
getChildren={(n) => (profile.nodes[n]!.children.length ? profile.nodes[n]!.children : undefined)}
|
|
isExpandable={(n) => profile.nodes[n]!.children.length > 0}
|
|
expanded={expanded ?? initial}
|
|
onExpandedChange={(next) => setExpanded(next)}
|
|
activateExpandable
|
|
onActivate={(n) => openFrame(profile, profile.nodes[n]!.frame)}
|
|
renderNode={(n) => {
|
|
const node = profile.nodes[n]!;
|
|
const location = frameLocation(profile, node.frame);
|
|
return (
|
|
<span className={styles.treeRow}>
|
|
<span className={styles.share}>{share(node.total ?? 0, total)}</span>
|
|
<span className={styles.name}>{profile.frames[node.frame]!.name}</span>
|
|
<TypeMark profile={profile} frame={node.frame} />
|
|
{location && <span className={styles.muted}>{location}</span>}
|
|
<span className={styles.weight}>
|
|
{formatWeight(node.total ?? 0, profile.unit)}
|
|
{(node.selfWeight ?? 0) > 0 && ` · self ${formatWeight(node.selfWeight ?? 0, profile.unit)}`}
|
|
</span>
|
|
</span>
|
|
);
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
type MethodSort = "self" | "total" | "name" | "calls";
|
|
const MAX_METHODS = 2000;
|
|
|
|
function MethodList({ profile, query }: { profile: Profile; query: string }) {
|
|
const tx = useTx();
|
|
const [sort, setSort] = useState<MethodSort>("self");
|
|
const [selected, setSelected] = useState<number | null>(null);
|
|
const total = profile.total ?? 0;
|
|
const counted = profile.methods.some((m) => m.calls !== null);
|
|
const rows = useMemo(() => {
|
|
const matches = matchingFrames(profile, query);
|
|
const list = profile.methods.filter((m) => !matches || matches.has(m.frame));
|
|
const name = (f: number) => profile.frames[f]!.name;
|
|
if (sort === "name") list.sort((a, b) => name(a.frame).localeCompare(name(b.frame)));
|
|
else if (sort === "total") list.sort((a, b) => (b.total ?? 0) - (a.total ?? 0));
|
|
else if (sort === "calls") list.sort((a, b) => (b.calls ?? 0) - (a.calls ?? 0));
|
|
return list.slice(0, MAX_METHODS);
|
|
}, [profile, query, sort]);
|
|
const sites = useMemo(() => (selected === null ? null : callSites(profile, selected)), [profile, selected]);
|
|
// Picking a caller or callee selects it in the list, even when the search hides it.
|
|
const select = (frame: number) => {
|
|
setSelected(frame);
|
|
if (!rows.some((m) => m.frame === frame)) useProfiler.setState({ query: "" });
|
|
};
|
|
useEffect(() => {
|
|
if (selected !== null) document.getElementById(`method-${selected}`)?.scrollIntoView?.({ block: "nearest" });
|
|
}, [selected]);
|
|
const header = (key: MethodSort, label: string) => (
|
|
<th aria-sort={sort === key ? (key === "name" ? "ascending" : "descending") : "none"}>
|
|
<button type="button" className={styles.headerCell} onClick={() => setSort(key)}>
|
|
{tx(label)}
|
|
</button>
|
|
</th>
|
|
);
|
|
return (
|
|
<div className={styles.methodPane}>
|
|
<div className={styles.tableScroll}>
|
|
<table className={styles.table} aria-label={tx("Method list")}>
|
|
<thead>
|
|
<tr>
|
|
{header("name", "Method")}
|
|
{header("self", "Self")}
|
|
{header("total", "Total")}
|
|
{counted && header("calls", "Calls")}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{rows.map((m) => {
|
|
const location = frameLocation(profile, m.frame);
|
|
return (
|
|
<tr
|
|
key={m.frame}
|
|
id={`method-${m.frame}`}
|
|
aria-selected={m.frame === selected}
|
|
className={clsx(m.frame === selected && styles.selectedRow)}
|
|
onClick={() => setSelected(m.frame)}
|
|
onDoubleClick={() => openFrame(profile, m.frame)}
|
|
>
|
|
<td className={styles.methodCell}>
|
|
<span className={styles.name}>{profile.frames[m.frame]!.name}</span>
|
|
<TypeMark profile={profile} frame={m.frame} />
|
|
{location && <span className={styles.muted}>{location}</span>}
|
|
</td>
|
|
<td className={styles.num}>
|
|
{formatWeight(m.selfWeight ?? 0, profile.unit)}{" "}
|
|
<span className={styles.muted}>{share(m.selfWeight ?? 0, total)}</span>
|
|
</td>
|
|
<td className={styles.num}>
|
|
{formatWeight(m.total ?? 0, profile.unit)}{" "}
|
|
<span className={styles.muted}>{share(m.total ?? 0, total)}</span>
|
|
</td>
|
|
{counted && (
|
|
<td className={styles.count}>{m.calls !== null ? formatCalls(m.calls, m.primitiveCalls) : ""}</td>
|
|
)}
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
{sites && selected !== null && (
|
|
<div className={styles.callSites}>
|
|
<CallSiteList title="Callers" profile={profile} sites={sites.callers} onSelect={select} />
|
|
<CallSiteList title="Callees" profile={profile} sites={sites.callees} onSelect={select} />
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** The callers or callees of the selected method: click selects one, double-click opens its source. */
|
|
function CallSiteList({
|
|
title,
|
|
profile,
|
|
sites,
|
|
onSelect,
|
|
}: {
|
|
title: string;
|
|
profile: Profile;
|
|
sites: CallSite[];
|
|
onSelect: (frame: number) => void;
|
|
}) {
|
|
const tx = useTx();
|
|
const total = profile.total ?? 0;
|
|
return (
|
|
<div className={styles.tableScroll}>
|
|
<table className={styles.table} aria-label={tx(title)}>
|
|
<thead>
|
|
<tr>
|
|
<th>
|
|
<span className={styles.headerCell}>{tx(title)}</span>
|
|
</th>
|
|
<th>
|
|
<span className={styles.headerCell}>{tx("Total")}</span>
|
|
</th>
|
|
{sites.some((x) => x.calls !== null) && (
|
|
<th>
|
|
<span className={styles.headerCell}>{tx("Calls")}</span>
|
|
</th>
|
|
)}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{sites.map((x) => {
|
|
const location = frameLocation(profile, x.frame);
|
|
return (
|
|
<tr key={x.frame} onClick={() => onSelect(x.frame)} onDoubleClick={() => openFrame(profile, x.frame)}>
|
|
<td className={styles.methodCell}>
|
|
<span className={styles.name}>{profile.frames[x.frame]!.name}</span>
|
|
{location && <span className={styles.muted}>{location}</span>}
|
|
</td>
|
|
<td className={styles.num}>
|
|
{formatWeight(x.total, profile.unit)} <span className={styles.muted}>{share(x.total, total)}</span>
|
|
</td>
|
|
{x.calls !== null && <td className={styles.count}>{formatCalls(x.calls, x.primitiveCalls)}</td>}
|
|
</tr>
|
|
);
|
|
})}
|
|
{!sites.length && (
|
|
<tr>
|
|
<td className={styles.muted}>
|
|
<T>None</T>
|
|
</td>
|
|
</tr>
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function ProfilerView() {
|
|
const tx = useTx();
|
|
const snapshot = useProfiler((s) => activeSnapshot(s));
|
|
const tab = useProfiler((s) => s.tab);
|
|
const query = useProfiler((s) => s.query);
|
|
if (!snapshot) {
|
|
return (
|
|
<EmptyState
|
|
title="No profiler snapshots"
|
|
actions={
|
|
<Button size="small" onClick={() => void executeAction("profiler.openSnapshot")}>
|
|
<T>Open Snapshot…</T>
|
|
</Button>
|
|
}
|
|
>
|
|
<span>
|
|
<T>Profile a run configuration to see where it spends its time.</T>
|
|
</span>
|
|
</EmptyState>
|
|
);
|
|
}
|
|
const profile = snapshot.profile;
|
|
return (
|
|
<div className={styles.view}>
|
|
<div className={styles.toolbar}>
|
|
<Tabs
|
|
variant="compact"
|
|
aria-label="Profiler views"
|
|
className={styles.viewTabs}
|
|
activeId={tab}
|
|
onSelect={(id) => useProfiler.setState({ tab: id as ProfilerTab })}
|
|
items={[
|
|
{ id: "flame", label: "Flame Graph" },
|
|
{ id: "tree", label: "Call Tree" },
|
|
{ id: "methods", label: "Method List" },
|
|
]}
|
|
/>
|
|
<span className={styles.muted}>{profileSummary(profile, tx)}</span>
|
|
{tab !== "tree" && (
|
|
<Input
|
|
className={styles.search}
|
|
placeholder="Search frames"
|
|
aria-label="Search frames"
|
|
value={query}
|
|
onChange={(e) => useProfiler.setState({ query: e.target.value })}
|
|
/>
|
|
)}
|
|
</div>
|
|
{snapshot.notice && (
|
|
<div className={styles.notice} role="status">
|
|
<Icon name="warning" size={13} className={styles.noticeIcon} />
|
|
<span>{tx(snapshot.notice)}</span>
|
|
</div>
|
|
)}
|
|
<div className={styles.body}>
|
|
{tab === "flame" && <FlameGraph key={snapshot.id} profile={profile} query={query} />}
|
|
{tab === "tree" && <CallTree key={snapshot.id} profile={profile} />}
|
|
{tab === "methods" && <MethodList key={snapshot.id} profile={profile} query={query} />}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|