-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.py
More file actions
328 lines (267 loc) · 10.8 KB
/
Copy pathdiff.py
File metadata and controls
328 lines (267 loc) · 10.8 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""Compare two profile reports and render a deterministic performance diff.
The public entry point is :func:`compare`, which returns a :class:`DiffResult`.
Rendering helpers turn that result into Markdown (the PR comment body), plain
text, or JSON.
Sign convention: a *positive* cumtime delta means the head branch got **slower**
(a regression); a negative delta means it got **faster** (an improvement).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from . import MARKER
# --------------------------------------------------------------------------- #
# Data model
# --------------------------------------------------------------------------- #
@dataclass
class FunctionDelta:
"""A single function's cumtime change between base and head."""
key: str
base_cumtime: Optional[float] # seconds; None if absent on base
head_cumtime: Optional[float] # seconds; None if absent on head
@property
def delta(self) -> float:
"""Head minus base cumtime in seconds (0 if either side missing)."""
if self.base_cumtime is None or self.head_cumtime is None:
return 0.0
return self.head_cumtime - self.base_cumtime
@property
def delta_pct(self) -> Optional[float]:
"""Percentage change relative to base; None when base is missing/zero."""
if self.base_cumtime is None or self.head_cumtime is None:
return None
if self.base_cumtime == 0:
return None
return (self.head_cumtime - self.base_cumtime) / self.base_cumtime * 100.0
@dataclass
class DiffResult:
"""The full comparison outcome."""
regressions: List[FunctionDelta] = field(default_factory=list)
improvements: List[FunctionDelta] = field(default_factory=list)
new_hotspots: List[FunctionDelta] = field(default_factory=list)
removed_hotspots: List[FunctionDelta] = field(default_factory=list)
base_total_s: float = 0.0
head_total_s: float = 0.0
base_peak_bytes: int = 0
head_peak_bytes: int = 0
has_regression: bool = False
@property
def total_delta_s(self) -> float:
return self.head_total_s - self.base_total_s
@property
def peak_delta_bytes(self) -> int:
return self.head_peak_bytes - self.base_peak_bytes
# --------------------------------------------------------------------------- #
# Comparison
# --------------------------------------------------------------------------- #
def _index(report: Dict) -> Dict[str, float]:
return {rec["key"]: float(rec["cumtime"]) for rec in report.get("functions", [])}
def compare(
base: Dict,
head: Dict,
*,
threshold_pct: float = 5.0,
min_abs_ms: float = 0.0,
top: int = 10,
) -> DiffResult:
"""Compare two report dicts and return a :class:`DiffResult`.
* ``threshold_pct`` — movements smaller than this percentage of the base
value are ignored (memory summary excluded).
* ``min_abs_ms`` — movements smaller than this absolute number of
milliseconds are ignored.
* ``top`` — how many movers to keep in each direction (and each new/removed
list).
"""
base_fns = _index(base)
head_fns = _index(head)
min_abs_s = min_abs_ms / 1000.0
regressions: List[FunctionDelta] = []
improvements: List[FunctionDelta] = []
new_hotspots: List[FunctionDelta] = []
removed_hotspots: List[FunctionDelta] = []
for key in base_fns.keys() | head_fns.keys():
b = base_fns.get(key)
h = head_fns.get(key)
fd = FunctionDelta(key=key, base_cumtime=b, head_cumtime=h)
if b is None:
new_hotspots.append(fd)
continue
if h is None:
removed_hotspots.append(fd)
continue
delta = fd.delta
if abs(delta) < min_abs_s:
continue
pct = fd.delta_pct
if pct is not None and abs(pct) < threshold_pct:
continue
if delta > 0:
regressions.append(fd)
elif delta < 0:
improvements.append(fd)
# Deterministic ordering.
regressions.sort(key=lambda d: (-d.delta, d.key))
improvements.sort(key=lambda d: (d.delta, d.key))
new_hotspots.sort(key=lambda d: (-(d.head_cumtime or 0.0), d.key))
removed_hotspots.sort(key=lambda d: (-(d.base_cumtime or 0.0), d.key))
result = DiffResult(
regressions=regressions[:top],
improvements=improvements[:top],
new_hotspots=new_hotspots[:top],
removed_hotspots=removed_hotspots[:top],
base_total_s=float(base.get("total_time_s", 0.0)),
head_total_s=float(head.get("total_time_s", 0.0)),
base_peak_bytes=int(base.get("memory", {}).get("peak_bytes", 0)),
head_peak_bytes=int(head.get("memory", {}).get("peak_bytes", 0)),
has_regression=bool(regressions),
)
return result
# --------------------------------------------------------------------------- #
# Formatting helpers
# --------------------------------------------------------------------------- #
def _fmt_ms(seconds: Optional[float]) -> str:
if seconds is None:
return "—"
return f"{seconds * 1000:.1f} ms"
def _fmt_delta_ms(seconds: float) -> str:
sign = "+" if seconds >= 0 else "−"
return f"{sign}{abs(seconds) * 1000:.1f} ms"
def _fmt_pct(pct: Optional[float]) -> str:
if pct is None:
return "—"
sign = "+" if pct >= 0 else "−"
return f"{sign}{abs(pct):.1f}%"
def _fmt_bytes(num: int) -> str:
value = float(num)
for unit in ("B", "KB", "MB", "GB"):
if abs(value) < 1024.0 or unit == "GB":
if unit == "B":
return f"{int(value)} {unit}"
return f"{value:.1f} {unit}"
value /= 1024.0
return f"{value:.1f} GB" # pragma: no cover
def _fmt_delta_bytes(num: int) -> str:
sign = "+" if num >= 0 else "−"
return f"{sign}{_fmt_bytes(abs(num))}"
def _arrow(delta: float) -> str:
if delta > 0:
return "▲"
if delta < 0:
return "▼"
return "▬"
# --------------------------------------------------------------------------- #
# Renderers
# --------------------------------------------------------------------------- #
def _mover_table(title: str, rows: List[FunctionDelta]) -> List[str]:
lines = [f"### {title}", ""]
lines.append("| Function | Base | Head | Δ | Δ% |")
lines.append("|---|---:|---:|---:|---:|")
for d in rows:
lines.append(
f"| `{d.key}` | {_fmt_ms(d.base_cumtime)} | {_fmt_ms(d.head_cumtime)} "
f"| {_fmt_delta_ms(d.delta)} | {_fmt_pct(d.delta_pct)} |"
)
lines.append("")
return lines
def _presence_table(title: str, rows: List[FunctionDelta], side: str) -> List[str]:
lines = [f"### {title}", ""]
lines.append("| Function | cumtime |")
lines.append("|---|---:|")
for d in rows:
value = d.head_cumtime if side == "head" else d.base_cumtime
lines.append(f"| `{d.key}` | {_fmt_ms(value)} |")
lines.append("")
return lines
def render_markdown(result: DiffResult) -> str:
"""Render *result* as the Markdown PR-comment body (marker included)."""
total_arrow = _arrow(result.total_delta_s)
mem_arrow = _arrow(result.peak_delta_bytes)
lines: List[str] = [MARKER, "## Performance profile diff", ""]
lines.append(
f"**Runtime (total cumtime):** {_fmt_ms(result.base_total_s)} → "
f"{_fmt_ms(result.head_total_s)} "
f"({_fmt_delta_ms(result.total_delta_s)} {total_arrow})"
)
lines.append("")
lines.append(
f"**Peak memory:** {_fmt_bytes(result.base_peak_bytes)} → "
f"{_fmt_bytes(result.head_peak_bytes)} "
f"({_fmt_delta_bytes(result.peak_delta_bytes)} {mem_arrow})"
)
lines.append("")
if result.regressions:
lines += _mover_table("Top regressions ▲ (slower)", result.regressions)
if result.improvements:
lines += _mover_table("Top improvements ▼ (faster)", result.improvements)
if result.new_hotspots:
lines += _presence_table("New hotspots", result.new_hotspots, "head")
if result.removed_hotspots:
lines += _presence_table("Removed hotspots", result.removed_hotspots, "base")
if not (
result.regressions
or result.improvements
or result.new_hotspots
or result.removed_hotspots
):
lines.append("_No function crossed the reporting thresholds._")
lines.append("")
lines.append(
"<sub>Generated by "
"[profile-diff-action](https://github.com/python-testing-debugging/profile-diff-action). "
"cumtime = cumulative time spent in a function and everything it calls.</sub>"
)
return "\n".join(lines).rstrip() + "\n"
def render_text(result: DiffResult) -> str:
"""Render a plain-text summary (no Markdown, no marker)."""
lines: List[str] = ["Performance profile diff", ""]
lines.append(
f"Runtime (total cumtime): {_fmt_ms(result.base_total_s)} -> "
f"{_fmt_ms(result.head_total_s)} ({_fmt_delta_ms(result.total_delta_s)})"
)
lines.append(
f"Peak memory: {_fmt_bytes(result.base_peak_bytes)} -> "
f"{_fmt_bytes(result.head_peak_bytes)} "
f"({_fmt_delta_bytes(result.peak_delta_bytes)})"
)
def block(title: str, rows: List[FunctionDelta]) -> None:
if not rows:
return
lines.append("")
lines.append(title)
for d in rows:
lines.append(
f" {d.key}: {_fmt_ms(d.base_cumtime)} -> {_fmt_ms(d.head_cumtime)} "
f"({_fmt_delta_ms(d.delta)}, {_fmt_pct(d.delta_pct)})"
)
block("Top regressions (slower):", result.regressions)
block("Top improvements (faster):", result.improvements)
block("New hotspots:", result.new_hotspots)
block("Removed hotspots:", result.removed_hotspots)
return "\n".join(lines) + "\n"
def render_json(result: DiffResult) -> Dict:
"""Render *result* as a JSON-serialisable dict."""
def rows(items: List[FunctionDelta]) -> List[Dict]:
return [
{
"key": d.key,
"base_cumtime": d.base_cumtime,
"head_cumtime": d.head_cumtime,
"delta": d.delta,
"delta_pct": d.delta_pct,
}
for d in items
]
return {
"summary": {
"base_total_s": result.base_total_s,
"head_total_s": result.head_total_s,
"total_delta_s": result.total_delta_s,
"base_peak_bytes": result.base_peak_bytes,
"head_peak_bytes": result.head_peak_bytes,
"peak_delta_bytes": result.peak_delta_bytes,
"has_regression": result.has_regression,
},
"regressions": rows(result.regressions),
"improvements": rows(result.improvements),
"new_hotspots": rows(result.new_hotspots),
"removed_hotspots": rows(result.removed_hotspots),
}