History

perf ilist: Add new python ilist command

The perf ilist command is a textual app [1] similar to perf list. In the top-left pane a tree of PMUs is displayed. Selecting a PMU expands the events within it. Selecting an event displays the `perf list` style event information in the top-right pane. When an event is selected it is opened and the counters on each CPU the event is for are periodically read. The bottom of the screen contains a scrollable set of sparklines showing the events in total and on each CPU. Scrolling below the sparklines shows the same data as raw counts. The sparklines are small graphs where the height of the bar is in relation to maximum of the other counts in the graph. By default the counts are read with an interval of 0.1 seconds (10 times per second). A -I/--interval command line option allows the interval to be changed. The oldest read counts are dropped when the counts fill the line causing the sparkline to move from right to left. A search box can be pulled up with the 's' key. 'n' and 'p' iterate through the search results. As some PMUs have hundreds of events a 'c' key will collapse the events in the current PMU to make navigating the PMUs easier. [1] https://textual.textualize.io/ Committer testing: This needs a bit more polishing, to test it I had to go thru some hops: $ python ilist python: can't open file '/home/acme/git/perf-tools-next/ilist': [Errno 2] No such file or directory $ $ python tools/perf/python/ilist.py Traceback (most recent call last): File "/home/acme/git/perf-tools-next/tools/perf/python/ilist.py", line 8, in <module> from textual import on ModuleNotFoundError: No module named 'textual' $ $ sudo dnf install textual Updating and loading repositories: Repositories loaded. Failed to resolve the transaction: No match for argument: textual You can try to add to command line: --skip-unavailable to skip unavailable packages $ After some searching I installed the 'python3-textual' and it starts, allowing traversing the various pmus and events, see descriptions on the upper right side and a view of the events on the lower half of the screen. Interesting for quickly iterating thru the available events.

Ian Rogers committed 1 year ago

Commit 83e5b8f1 parent 2f20df51 file · +385 −0Browse files

Showing the changes to tools/perf/python (1 of 1 file). Show all

Unified · Split

tools/perf/python/ilist.py+385−0
@@ -0,0 +1,385 @@
1#!/usr/bin/env python3
2# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
3"""Interactive perf list."""
4
5import argparse
6from typing import Any, Dict, Optional, Tuple
7import perf
8from textual import on
9from textual.app import App, ComposeResult
10from textual.binding import Binding
11from textual.containers import Horizontal, HorizontalGroup, Vertical, VerticalScroll
12from textual.command import SearchIcon
13from textual.screen import ModalScreen
14from textual.widgets import Button, Footer, Header, Input, Label, Sparkline, Static, Tree
15from textual.widgets.tree import TreeNode
16
17
18class ErrorScreen(ModalScreen[bool]):
19 """Pop up dialog for errors."""
20
21 CSS = """
22 ErrorScreen {
23 align: center middle;
24 }
25 """
26
27 def __init__(self, error: str):
28 self.error = error
29 super().__init__()
30
31 def compose(self) -> ComposeResult:
32 yield Button(f"Error: {self.error}", variant="primary", id="error")
33
34 def on_button_pressed(self, event: Button.Pressed) -> None:
35 self.dismiss(True)
36
37
38class SearchScreen(ModalScreen[str]):
39 """Pop up dialog for search."""
40
41 CSS = """
42 SearchScreen Horizontal {
43 align: center middle;
44 margin-top: 1;
45 }
46 SearchScreen Input {
47 width: 1fr;
48 }
49 """
50
51 def compose(self) -> ComposeResult:
52 yield Horizontal(SearchIcon(), Input(placeholder="Event name"))
53
54 def on_input_submitted(self, event: Input.Submitted) -> None:
55 """Handle the user pressing Enter in the input field."""
56 self.dismiss(event.value)
57
58
59class Counter(HorizontalGroup):
60 """Two labels for a CPU and its counter value."""
61
62 CSS = """
63 Label {
64 gutter: 1;
65 }
66 """
67
68 def __init__(self, cpu: int) -> None:
69 self.cpu = cpu
70 super().__init__()
71
72 def compose(self) -> ComposeResult:
73 label = f"cpu{self.cpu}" if self.cpu >= 0 else "total"
74 yield Label(label + " ")
75 yield Label("0", id=f"counter_{label}")
76
77
78class CounterSparkline(HorizontalGroup):
79 """A Sparkline for a performance counter."""
80
81 def __init__(self, cpu: int) -> None:
82 self.cpu = cpu
83 super().__init__()
84
85 def compose(self) -> ComposeResult:
86 label = f"cpu{self.cpu}" if self.cpu >= 0 else "total"
87 yield Label(label)
88 yield Sparkline([], summary_function=max, id=f"sparkline_{label}")
89
90
91class IListApp(App):
92 TITLE = "Interactive Perf List"
93
94 BINDINGS = [
95 Binding(key="s", action="search", description="Search",
96 tooltip="Search events and PMUs"),
97 Binding(key="n", action="next", description="Next",
98 tooltip="Next search result or item"),
99 Binding(key="p", action="prev", description="Previous",
100 tooltip="Previous search result or item"),
101 Binding(key="c", action="collapse", description="Collapse",
102 tooltip="Collapse the current PMU"),
103 Binding(key="^q", action="quit", description="Quit",
104 tooltip="Quit the app"),
105 ]
106
107 CSS = """
108 /* Make the 'total' sparkline a different color. */
109 #sparkline_total > .sparkline--min-color {
110 color: $accent;
111 }
112 #sparkline_total > .sparkline--max-color {
113 color: $accent 30%;
114 }
115 /*
116 * Make the active_search initially not displayed with the text in
117 * the middle of the line.
118 */
119 #active_search {
120 display: none;
121 width: 100%;
122 text-align: center;
123 }
124 """
125
126 def __init__(self, interval: float) -> None:
127 self.interval = interval
128 self.evlist = None
129 self.search_results: list[TreeNode[str]] = []
130 self.cur_search_result: TreeNode[str] | None = None
131 super().__init__()
132
133 def expand_and_select(self, node: TreeNode[Any]) -> None:
134 """Expand select a node in the tree."""
135 if node.parent:
136 node.parent.expand()
137 if node.parent.parent:
138 node.parent.parent.expand()
139 node.expand()
140 node.tree.select_node(node)
141 node.tree.scroll_to_node(node)
142
143 def set_searched_tree_node(self, previous: bool) -> None:
144 """Set the cur_search_result node to either the next or previous."""
145 l = len(self.search_results)
146
147 if l < 1:
148 tree: Tree[str] = self.query_one("#pmus", Tree)
149 if previous:
150 tree.action_cursor_up()
151 else:
152 tree.action_cursor_down()
153 return
154
155 if self.cur_search_result:
156 idx = self.search_results.index(self.cur_search_result)
157 if previous:
158 idx = idx - 1 if idx > 0 else l - 1
159 else:
160 idx = idx + 1 if idx < l - 1 else 0
161 else:
162 idx = l - 1 if previous else 0
163
164 node = self.search_results[idx]
165 if node == self.cur_search_result:
166 return
167
168 self.cur_search_result = node
169 self.expand_and_select(node)
170
171 def action_search(self) -> None:
172 """Search was chosen."""
173 def set_initial_focus(event: str | None) -> None:
174 """Sets the focus after the SearchScreen is dismissed."""
175
176 search_label = self.query_one("#active_search", Label)
177 search_label.display = True if event else False
178 if not event:
179 return
180 event = event.lower()
181 search_label.update(f'Searching for events matching "{event}"')
182
183 tree: Tree[str] = self.query_one("#pmus", Tree)
184
185 def find_search_results(event: str, node: TreeNode[str],
186 cursor_seen: bool = False,
187 match_after_cursor: Optional[TreeNode[str]] = None
188 ) -> Tuple[bool, Optional[TreeNode[str]]]:
189 """Find nodes that match the search remembering the one after the cursor."""
190 if not cursor_seen and node == tree.cursor_node:
191 cursor_seen = True
192 if node.data and event in node.data:
193 if cursor_seen and not match_after_cursor:
194 match_after_cursor = node
195 self.search_results.append(node)
196
197 if node.children:
198 for child in node.children:
199 (cursor_seen, match_after_cursor) = \
200 find_search_results(event, child, cursor_seen, match_after_cursor)
201 return (cursor_seen, match_after_cursor)
202
203 self.search_results.clear()
204 (_, self.cur_search_result) = find_search_results(event, tree.root)
205 if len(self.search_results) < 1:
206 self.push_screen(ErrorScreen(f"Failed to find pmu/event {event}"))
207 search_label.display = False
208 elif self.cur_search_result:
209 self.expand_and_select(self.cur_search_result)
210 else:
211 self.set_searched_tree_node(previous=False)
212
213 self.push_screen(SearchScreen(), set_initial_focus)
214
215 def action_next(self) -> None:
216 """Next was chosen."""
217 self.set_searched_tree_node(previous=False)
218
219 def action_prev(self) -> None:
220 """Previous was chosen."""
221 self.set_searched_tree_node(previous=True)
222
223 def action_collapse(self) -> None:
224 """Collapse the potentially large number of events under a PMU."""
225 tree: Tree[str] = self.query_one("#pmus", Tree)
226 node = tree.cursor_node
227 if node and node.parent and node.parent.parent:
228 node.parent.collapse_all()
229 node.tree.scroll_to_node(node.parent)
230
231 def update_counts(self) -> None:
232 """Called every interval to update counts."""
233 if not self.evlist:
234 return
235
236 def update_count(cpu: int, count: int):
237 # Update the raw count display.
238 counter: Label = self.query(f"#counter_cpu{cpu}" if cpu >= 0 else "#counter_total")
239 if not counter:
240 return
241 counter = counter.first(Label)
242 counter.update(str(count))
243
244 # Update the sparkline.
245 line: Sparkline = self.query(f"#sparkline_cpu{cpu}" if cpu >= 0 else "#sparkline_total")
246 if not line:
247 return
248 line = line.first(Sparkline)
249 # If there are more events than the width, remove the front event.
250 if len(line.data) > line.size.width:
251 line.data.pop(0)
252 line.data.append(count)
253 line.mutate_reactive(Sparkline.data)
254
255 # Update the total and each CPU counts, assume there's just 1 evsel.
256 total = 0
257 self.evlist.disable()
258 for evsel in self.evlist:
259 for cpu in evsel.cpus():
260 aggr = 0
261 for thread in evsel.threads():
262 counts = evsel.read(cpu, thread)
263 aggr += counts.val
264 update_count(cpu, aggr)
265 total += aggr
266 update_count(-1, total)
267 self.evlist.enable()
268
269 def on_mount(self) -> None:
270 """When App starts set up periodic event updating."""
271 self.update_counts()
272 self.set_interval(self.interval, self.update_counts)
273
274 def set_pmu_and_event(self, pmu: str, event: str) -> None:
275 """Updates the event/description and starts the counters."""
276 # Remove previous event information.
277 if self.evlist:
278 self.evlist.disable()
279 self.evlist.close()
280 lines = self.query(CounterSparkline)
281 for line in lines:
282 line.remove()
283 lines = self.query(Counter)
284 for line in lines:
285 line.remove()
286
287 def pmu_event_description(pmu: str, event: str) -> str:
288 """Find and format event description for {pmu}/{event}/."""
289 def get_info(info: Dict[str, str], key: str):
290 return (info[key] + "\n") if key in info else ""
291
292 for p in perf.pmus():
293 if p.name() != pmu:
294 continue
295 for info in p.events():
296 if "name" not in info or info["name"] != event:
297 continue
298
299 desc = get_info(info, "topic")
300 desc += get_info(info, "event_type_desc")
301 desc += get_info(info, "desc")
302 desc += get_info(info, "long_desc")
303 desc += get_info(info, "encoding_desc")
304 return desc
305 return "description"
306
307 # Parse event, update event text and description.
308 full_name = event if event.startswith(pmu) or ':' in event else f"{pmu}/{event}/"
309 self.query_one("#event_name", Label).update(full_name)
310 self.query_one("#event_description", Static).update(pmu_event_description(pmu, event))
311
312 # Open the event.
313 try:
314 self.evlist = perf.parse_events(full_name)
315 if self.evlist:
316 self.evlist.open()
317 self.evlist.enable()
318 except:
319 self.evlist = None
320
321 if not self.evlist:
322 self.push_screen(ErrorScreen(f"Failed to open {full_name}"))
323 return
324
325 # Add spark lines for all the CPUs. Note, must be done after
326 # open so that the evlist CPUs have been computed by propagate
327 # maps.
328 lines = self.query_one("#lines")
329 line = CounterSparkline(cpu=-1)
330 lines.mount(line)
331 for cpu in self.evlist.all_cpus():
332 line = CounterSparkline(cpu)
333 lines.mount(line)
334 line = Counter(cpu=-1)
335 lines.mount(line)
336 for cpu in self.evlist.all_cpus():
337 line = Counter(cpu)
338 lines.mount(line)
339
340 def compose(self) -> ComposeResult:
341 """Draws the app."""
342 def pmu_event_tree() -> Tree:
343 """Create tree of PMUs with events under."""
344 tree: Tree[str] = Tree("PMUs", id="pmus")
345 tree.root.expand()
346 for pmu in perf.pmus():
347 pmu_name = pmu.name().lower()
348 pmu_node = tree.root.add(pmu_name, data=pmu_name)
349 try:
350 for event in sorted(pmu.events(), key=lambda x: x["name"]):
351 if "name" in event:
352 e = event["name"].lower()
353 if "alias" in event:
354 pmu_node.add_leaf(f'{e} ({event["alias"]})', data=e)
355 else:
356 pmu_node.add_leaf(e, data=e)
357 except:
358 # Reading events may fail with EPERM, ignore.
359 pass
360 return tree
361
362 yield Header(id="header")
363 yield Horizontal(Vertical(pmu_event_tree(), id="events"),
364 Vertical(Label("event name", id="event_name"),
365 Static("description", markup=False, id="event_description"),
366 ))
367 yield Label(id="active_search")
368 yield VerticalScroll(id="lines")
369 yield Footer(id="footer")
370
371 @on(Tree.NodeSelected)
372 def on_tree_node_selected(self, event: Tree.NodeSelected[str]) -> None:
373 """Called when a tree node is selected, selecting the event."""
374 if event.node.parent and event.node.parent.parent:
375 assert event.node.parent.data is not None
376 assert event.node.data is not None
377 self.set_pmu_and_event(event.node.parent.data, event.node.data)
378
379
380if __name__ == "__main__":
381 ap = argparse.ArgumentParser()
382 ap.add_argument('-I', '--interval', help="Counter update interval in seconds", default=0.1)
383 args = ap.parse_args()
384 app = IListApp(float(args.interval))
385 app.run()