From nobody Wed Oct 8 14:42:40 2025 Received: from mail-pj1-f74.google.com (mail-pj1-f74.google.com [209.85.216.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9971C207A0B for ; Sat, 28 Jun 2025 00:10:10 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751069412; cv=none; b=sMj/y7SwMqNQagkGeqIc1DV8FqTMWY1rXWQi53BjNWCTlNVMZGS8H3BeMqN4YAY4k5xrVjulJNgLW1/8rL3YRvIgaBjFszVSYpPAoU0DZ3/3PZUn+R4LfTfvmGtNHmvv5lB23q+k+3xliE7VRrZCV74EZ0mDaziTEK89PTa3G84= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751069412; c=relaxed/simple; bh=D1meKHm9HLxVcV+eADlMNBj+6b4Bh9wc5AOyxldTOIA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Content-Type; b=pJtEjpKUzm6KZWmrW7S3In3ejN+Pa3CpjFAM+DrCbZIDtqtvGutVlwiqeLNIm8bXSNuno7WVzl7Z0ITP9MwovfYaHpcVuLmHBc1x/1J5G1QnKMbI3I4Ah61qTsnZHgAX5q8cc8OzkOG49+O8LBsKSpy/CWLOaAS4oZCfsJU7vTI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=sh1wAB4R; arc=none smtp.client-ip=209.85.216.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="sh1wAB4R" Received: by mail-pj1-f74.google.com with SMTP id 98e67ed59e1d1-311a6b43ed7so84403a91.1 for ; Fri, 27 Jun 2025 17:10:10 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1751069410; x=1751674210; darn=vger.kernel.org; h=to:from:subject:message-id:references:mime-version:in-reply-to:date :from:to:cc:subject:date:message-id:reply-to; bh=bWGI+WCsIN51TDRPS0BPiVuu9g5rUZhDYM76R7qcpLA=; b=sh1wAB4Req3TMH5QoF2wxxvJ+9lGBF4uImA/x8kBAH2Z69m4RZLeLWDHSUijqQmqXw zoNeidSt04cf4Ddg6h8viSFc38euNjFsRU/4nNE388YatNCXz4b5Gq8aZt0C7vYtFCf2 Aa4HneTrAb57Jard+kT/873XktRuVfiaJZHfPu+z0HyXxbu85m51AzUaTGcY8iSdHi0U gqODBzOKopx6v7fRsbltN1w9PkonUQN9Moz4bl6rdgWjDclRJq6PDT99lDJ1VPMnTbr6 d5YyShnigiHmmcwzxsNtAFAZe8GlqcihN7rnM1RQVLzzGP47l5bwzeWW1MBsArtFdVCv OAAg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751069410; x=1751674210; h=to:from:subject:message-id:references:mime-version:in-reply-to:date :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=bWGI+WCsIN51TDRPS0BPiVuu9g5rUZhDYM76R7qcpLA=; b=rwU583fT+8FjDxeFMkqqbETKMcNhMBz7aDvKxrHd3BKnOLXe7dzE9WjZtuHgk6dzbM LzJD9k9FeMA/vzAsMCzG1Sgwf5uL95qTUCoVXN0L8C21DRC8cHeaHUKmd7iQWU8nLpi7 hipQcugCUWiZBX9a86alfTsUfM9r9hA+NxA7L22uzKDYvBjRed4usrtSFu1ZbttYbXxU Jmx/Xzvc4UmvWXHW+6dGquWv6aHaPNEc3kAMPL5clBQ15PdStFxdHWdzHeVQ1jnOYD3w W59XMCFYZBaQ5rCjyCLCLgbz9B/VER/zyHgtN1/sUwsKZIftnnuiABe9aHacnVez2l5A smYg== X-Forwarded-Encrypted: i=1; AJvYcCXgAG4tSq/JEIY20pmV1hsuf6vIkdLlQ6IgYdpkqImXjmBRrgFGmoyguNIoo3G+1n5NdENn1POTURqKJfQ=@vger.kernel.org X-Gm-Message-State: AOJu0YwM+q5R/jQyaBWti0NVW1nb/P342CtH2IDMU8V3JSAloSgY8inh 5gJE/WXw0sYfbFX4ZaVRRVODrDe1QAJr/cXbErXb84h4nx6tWxzlzrbDZzMBPwApd9lGSSAAbdv XpFA/6mKnrQ== X-Google-Smtp-Source: AGHT+IGAwnQyRjSgbgapVtoxeh23DljPd0BCoh547jG6xOR+St+CLwjz42P/Xrk5blh9oBXNXXcTwhqXrctn X-Received: from pjbcz16.prod.google.com ([2002:a17:90a:d450:b0:313:2ad9:17ec]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a17:90b:5347:b0:311:e8cc:4255 with SMTP id 98e67ed59e1d1-318c930f93amr6304809a91.31.1751069409879; Fri, 27 Jun 2025 17:10:09 -0700 (PDT) Date: Fri, 27 Jun 2025 17:09:29 -0700 In-Reply-To: <20250628000929.230406-1-irogers@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250628000929.230406-1-irogers@google.com> X-Mailer: git-send-email 2.50.0.727.gbf7dc18ff4-goog Message-ID: <20250628000929.230406-16-irogers@google.com> Subject: [PATCH v4 15/15] perf ilist: Add new python ilist command From: Ian Rogers To: Peter Zijlstra , Ingo Molnar , Arnaldo Carvalho de Melo , Namhyung Kim , Mark Rutland , Alexander Shishkin , Jiri Olsa , Ian Rogers , Adrian Hunter , Kan Liang , James Clark , Xu Yang , John Garry , "Masami Hiramatsu (Google)" , Howard Chu , Weilin Wang , Thomas Richter , Andi Kleen , Tiezhu Yang , Gautam Menghani , linux-kernel@vger.kernel.org, linux-perf-users@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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/ Signed-off-by: Ian Rogers --- tools/perf/python/ilist.py | 376 +++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100755 tools/perf/python/ilist.py diff --git a/tools/perf/python/ilist.py b/tools/perf/python/ilist.py new file mode 100755 index 000000000000..b986447f8831 --- /dev/null +++ b/tools/perf/python/ilist.py @@ -0,0 +1,376 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +"""Interactive perf list.""" + +import argparse +from typing import Any, Dict, Tuple +import perf +from textual import on +from textual.app import App, ComposeResult +from textual.binding import Binding +from textual.containers import Horizontal, HorizontalGroup, Vertical, Vert= icalScroll +from textual.command import SearchIcon +from textual.screen import ModalScreen +from textual.widgets import Button, Footer, Header, Input, Label, Sparklin= e, Static, Tree +from textual.widgets.tree import TreeNode + +class ErrorScreen(ModalScreen[bool]): + """Pop up dialog for errors.""" + + CSS=3D""" + ErrorScreen { + align: center middle; + } + """ + def __init__(self, error: str): + self.error =3D error + super().__init__() + + def compose(self) -> ComposeResult: + yield Button(f"Error: {self.error}", variant=3D"primary", id=3D"er= ror") + + def on_button_pressed(self, event: Button.Pressed) -> None: + self.dismiss(True) + + +class SearchScreen(ModalScreen[str]): + """Pop up dialog for search.""" + + CSS=3D""" + SearchScreen Horizontal { + align: center middle; + margin-top: 1; + } + SearchScreen Input { + width: 1fr; + } + """ + def compose(self) -> ComposeResult: + yield Horizontal(SearchIcon(), Input(placeholder=3D"Event name")) + + def on_input_submitted(self, event: Input.Submitted) -> None: + """Handle the user pressing Enter in the input field.""" + self.dismiss(event.value) + + +class Counter(HorizontalGroup): + """Two labels for a CPU and its counter value.""" + + CSS=3D""" + Label { + gutter: 1; + } + """ + + def __init__(self, cpu: int) -> None: + self.cpu =3D cpu + super().__init__() + + def compose(self) -> ComposeResult: + label =3D f"cpu{self.cpu}" if self.cpu >=3D 0 else "total" + yield Label(label + " ") + yield Label("0", id=3Df"counter_{label}") + + +class CounterSparkline(HorizontalGroup): + """A Sparkline for a performance counter.""" + + def __init__(self, cpu: int) -> None: + self.cpu =3D cpu + super().__init__() + + def compose(self) -> ComposeResult: + label =3D f"cpu{self.cpu}" if self.cpu >=3D 0 else "total" + yield Label(label) + yield Sparkline([], summary_function=3Dmax, id=3Df"sparkline_{labe= l}") + + +class IListApp(App): + TITLE =3D "Interactive Perf List" + + BINDINGS =3D [ + Binding(key=3D"s", action=3D"search", description=3D"Search", + tooltip=3D"Search events and PMUs"), + Binding(key=3D"n", action=3D"next", description=3D"Next", + tooltip=3D"Next search result or item"), + Binding(key=3D"p", action=3D"prev", description=3D"Previous", + tooltip=3D"Previous search result or item"), + Binding(key=3D"q", action=3D"quit", description=3D"Quit the app"), + Binding(key=3D"c", action=3D"collapse", description=3D"Collapse", + tooltip=3D"Collapse the current PMU"), + ] + + # Make the 'total' sparkline a different color. + CSS =3D """ + #sparkline_total > .sparkline--min-color { + color: $accent; + } + #sparkline_total > .sparkline--max-color { + color: $accent 30%; + } + """ + + + def __init__(self, interval: float) -> None: + self.interval =3D interval + self.evlist =3D None + self.search_results: list[TreeNode[str]] =3D [] + self.cur_search_result: TreeNode[str] | None =3D None + super().__init__() + + + + def expand_and_select(self, node: TreeNode[Any]) -> None: + """Expand select a node in the tree.""" + if node.parent: + node.parent.expand() + if node.parent.parent: + node.parent.parent.expand() + node.expand() + node.tree.select_node(node) + node.tree.scroll_to_node(node) + + + def set_searched_tree_node(self, previous: bool) -> None: + """Set the cur_search_result node to either the next or previous."= "" + l =3D len(self.search_results) + + if l < 1: + tree: Tree[str] =3D self.query_one("#pmus", Tree) + if previous: + tree.action_cursor_up() + else: + tree.action_cursor_down() + return + + if self.cur_search_result: + idx =3D self.search_results.index(self.cur_search_result) + if previous: + idx =3D idx - 1 if idx > 0 else l - 1 + else: + idx =3D idx + 1 if idx < l - 1 else 0 + else: + idx =3D l - 1 if previous else 0 + + node =3D self.search_results[idx] + if node =3D=3D self.cur_search_result: + return + + self.cur_search_result =3D node + self.expand_and_select(node) + + def action_search(self) -> None: + """Search was chosen.""" + def set_initial_focus(event: str | None) -> None: + """Sets the focus after the SearchScreen is dismissed.""" + if not event: + return + + event =3D event.lower() + self.query_one("#active_search", Label) \ + .update(f'Searching for events matching "{event}"') + tree: Tree[str] =3D self.query_one("#pmus", Tree) + def find_search_results(event: str, node: TreeNode[str], \ + cursor_seen: bool =3D False, \ + match_after_cursor: TreeNode[str] | No= ne =3D None) \ + -> Tuple[bool, TreeNode[str] | None]: + """Find nodes that match the search remembering the one af= ter the cursor.""" + if not cursor_seen and node =3D=3D tree.cursor_node: + cursor_seen =3D True + if node.data and event in node.data: + if cursor_seen and not match_after_cursor: + match_after_cursor =3D node + self.search_results.append(node) + + if node.children: + for child in node.children: + (cursor_seen, match_after_cursor) =3D \ + find_search_results(event, child, cursor_seen,= match_after_cursor) + return (cursor_seen, match_after_cursor) + + self.search_results.clear() + (_ , self.cur_search_result) =3D find_search_results(event, tr= ee.root) + if len(self.search_results) < 1: + self.push_screen(ErrorScreen(f"Failed to find pmu/event {e= vent}")) + elif self.cur_search_result: + self.expand_and_select(self.cur_search_result) + else: + self.set_searched_tree_node(previous=3DFalse) + + self.push_screen(SearchScreen(), set_initial_focus) + + + def action_next(self) -> None: + """Next was chosen.""" + self.set_searched_tree_node(previous=3DFalse) + + + def action_prev(self) -> None: + """Previous was chosen.""" + self.set_searched_tree_node(previous=3DTrue) + + + def action_collapse(self) -> None: + """Collapse the potentially large number of events under a PMU.""" + tree: Tree[str] =3D self.query_one("#pmus", Tree) + node =3D tree.cursor_node + if node and node.parent and node.parent.parent: + node.parent.collapse_all() + node.tree.scroll_to_node(node.parent) + + + def update_counts(self) -> None: + """Called every interval to update counts.""" + if not self.evlist: + return + + def update_count(cpu: int, count: int): + # Update the raw count display. + counter: Label =3D self.query(f"#counter_cpu{cpu}" if cpu >=3D= 0 else "#counter_total") + if not counter: + return + counter =3D counter.first(Label) + counter.update(str(count)) + + # Update the sparkline. + line: Sparkline =3D self.query(f"#sparkline_cpu{cpu}" if cpu >= =3D 0 else "#sparkline_total") + if not line: + return + line =3D line.first(Sparkline) + # If there are more events than the width, remove the front ev= ent. + if len(line.data) > line.size.width: + line.data.pop(0) + line.data.append(count) + line.mutate_reactive(Sparkline.data) + + # Update the total and each CPU counts, assume there's just 1 evse= l. + total =3D 0 + self.evlist.disable() + for evsel in self.evlist: + for cpu in evsel.cpus(): + aggr =3D 0 + for thread in evsel.threads(): + counts =3D evsel.read(cpu, thread) + aggr +=3D counts.val + update_count(cpu, aggr) + total +=3D aggr + update_count(-1, total) + self.evlist.enable() + + + def on_mount(self) -> None: + """When App starts set up periodic event updating.""" + self.update_counts() + self.set_interval(self.interval, self.update_counts) + + + def set_pmu_and_event(self, pmu: str, event: str) -> None: + """Updates the event/description and starts the counters.""" + # Remove previous event information. + if self.evlist: + self.evlist.disable() + self.evlist.close() + lines =3D self.query(CounterSparkline) + for line in lines: + line.remove() + lines =3D self.query(Counter) + for line in lines: + line.remove() + + def pmu_event_description(pmu: str, event: str) -> str: + """Find and format event description for {pmu}/{event}/.""" + def get_info(info: Dict[str, str], key: str): + return (info[key] + "\n") if key in info else "" + + for p in perf.pmus(): + if p.name() !=3D pmu: + continue + for info in p.events(): + if "name" not in info or info["name"] !=3D event: + continue + + desc =3D get_info(info, "topic") + desc +=3D get_info(info, "event_type_desc") + desc +=3D get_info(info, "desc") + desc +=3D get_info(info, "long_desc") + desc +=3D get_info(info, "encoding_desc") + return desc + return "description" + + # Parse event, update event text and description. + full_name =3D event if event.startswith(pmu) or ':' in event else = f"{pmu}/{event}/" + self.query_one("#event_name", Label).update(full_name) + self.query_one("#event_description", Static).update(pmu_event_desc= ription(pmu, event)) + + # Open the event. + try: + self.evlist =3D perf.parse_events(full_name) + if self.evlist: + self.evlist.open() + self.evlist.enable() + except: + self.evlist =3D None + + if not self.evlist: + self.push_screen(ErrorScreen(f"Failed to open {full_name}")) + return + + # Add spark lines for all the CPUs. Note, must be done after + # open so that the evlist CPUs have been computed by propagate + # maps. + lines =3D self.query_one("#lines") + line =3D CounterSparkline(cpu=3D-1) + lines.mount(line) + for cpu in self.evlist.all_cpus(): + line =3D CounterSparkline(cpu) + lines.mount(line) + line =3D Counter(cpu=3D-1) + lines.mount(line) + for cpu in self.evlist.all_cpus(): + line =3D Counter(cpu) + lines.mount(line) + + + def compose(self) -> ComposeResult: + """Draws the app.""" + def pmu_event_tree() -> Tree: + """Create tree of PMUs with events under.""" + tree: Tree[str] =3D Tree("PMUs", id=3D"pmus") + tree.root.expand() + for pmu in perf.pmus(): + pmu_name =3D pmu.name().lower() + pmu_node =3D tree.root.add(pmu_name, data=3Dpmu_name) + for event in sorted(pmu.events(), key=3Dlambda x: x["name"= ]): + if "name" in event: + e =3D event["name"].lower() + if "alias" in event: + pmu_node.add_leaf(f'{e} ({event["alias"]})', d= ata=3De) + else: + pmu_node.add_leaf(e, data=3De) + return tree + + yield Header(id=3D"header") + yield Horizontal(Vertical(pmu_event_tree(), id=3D"events"), + Vertical(Label("event name", id=3D"event_name"), + Static("description", markup=3DFalse, id= =3D"event_description"), + Label(id=3D"active_search") + )) + yield VerticalScroll(id=3D"lines") + yield Footer(id=3D"footer") + + + @on(Tree.NodeSelected) + def on_tree_node_selected(self, event: Tree.NodeSelected[str]) -> None: + """Called when a tree node is selected, selecting the event.""" + if event.node.parent and event.node.parent.parent: + assert event.node.parent.data is not None + assert event.node.data is not None + self.set_pmu_and_event(event.node.parent.data, event.node.data) + + +if __name__ =3D=3D "__main__": + ap =3D argparse.ArgumentParser() + ap.add_argument('-I', '--interval', help=3D"Counter update interval in= seconds", default=3D0.1) + args =3D ap.parse_args() + app =3D IListApp(float(args.interval)) + app.run() --=20 2.50.0.727.gbf7dc18ff4-goog