[PATCH v1 33/49] perf python: Port wakeup-latency from Perl to perf module

From: Ian Rogers

Date: Sun Sep 20 2026 - 01:32:10 EST


Replace the legacy Perl script wakeup-latency.pl with a standalone
Python script in tools/perf/python/wakeup-latency.py using the perf
Python module.

Improvements compared to the legacy Perl script:
- Remove the dependency on libperl and Perf::Trace::Util.
- Guard print_totals() when total_wakeups == 0 (printing 'N/A' instead
of dividing by zero when a trace contains no matched wakeup/switch
pairs).
- Add argparse CLI options (-i/--input) and full type annotations.

Add a shell test
(test_wakeup_latency_python.sh) to verify the standalone script.

Assisted-by: Antigravity:gemini-3.1-pro
Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
---
tools/perf/python/wakeup-latency.py | 94 +++++++++++++++++++
.../tests/shell/test_wakeup_latency_python.sh | 83 ++++++++++++++++
2 files changed, 177 insertions(+)
create mode 100755 tools/perf/python/wakeup-latency.py
create mode 100755 tools/perf/tests/shell/test_wakeup_latency_python.sh

diff --git a/tools/perf/python/wakeup-latency.py b/tools/perf/python/wakeup-latency.py
new file mode 100755
index 000000000000..6113fa92b501
--- /dev/null
+++ b/tools/perf/python/wakeup-latency.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only
+"""Display avg/min/max wakeup latency."""
+from __future__ import annotations
+
+import argparse
+from collections import defaultdict
+import sys
+from typing import Optional, Dict
+import perf
+
+class WakeupLatency:
+ """Tracks and displays wakeup latency statistics."""
+ def __init__(self) -> None:
+ self.last_wakeup: Dict[int, int] = defaultdict(int)
+ self.max_wakeup_latency: int = 0
+ self.min_wakeup_latency: Optional[int] = None
+ self.total_wakeup_latency = 0
+ self.total_wakeups = 0
+ self.unhandled: Dict[str, int] = defaultdict(int)
+ self.session: Optional[perf.session] = None
+
+ def process_event(self, sample: perf.sample_event) -> None:
+ """Process events."""
+ event_name = str(sample.evsel)
+ sample_time = sample.sample_time
+
+ if "sched:sched_wakeup" in event_name:
+ try:
+ pid = sample.pid
+ self.last_wakeup[pid] = sample_time
+ except AttributeError:
+ self.unhandled[event_name] += 1
+ elif "sched:sched_switch" in event_name:
+ try:
+ next_pid = sample.next_pid
+ wakeup_ts = self.last_wakeup.get(next_pid, 0)
+ if wakeup_ts:
+ latency = sample_time - wakeup_ts
+ self.max_wakeup_latency = max(self.max_wakeup_latency, latency)
+ if self.min_wakeup_latency is None:
+ self.min_wakeup_latency = latency
+ else:
+ self.min_wakeup_latency = min(self.min_wakeup_latency, latency)
+ self.total_wakeup_latency += latency
+ self.total_wakeups += 1
+ del self.last_wakeup[next_pid]
+ except AttributeError:
+ self.unhandled[event_name] += 1
+ else:
+ self.unhandled[event_name] += 1
+
+ def print_totals(self) -> None:
+ """Print summary statistics."""
+ print("wakeup_latency stats:\n")
+ print(f"total_wakeups: {self.total_wakeups}")
+ if self.total_wakeups:
+ avg = self.total_wakeup_latency // self.total_wakeups
+ print(f"avg_wakeup_latency (ns): {avg}")
+ print(f"min_wakeup_latency (ns): {self.min_wakeup_latency}")
+ print(f"max_wakeup_latency (ns): {self.max_wakeup_latency}")
+ else:
+ print("avg_wakeup_latency (ns): N/A")
+ print("min_wakeup_latency (ns): N/A")
+ print("max_wakeup_latency (ns): N/A")
+
+ if self.unhandled:
+ print("\nunhandled events:\n")
+ print(f"{'event':<40s} {'count':>10s}")
+ print(f"{'-'*40} {'-'*10}")
+ for event_name, count in self.unhandled.items():
+ print(f"{event_name:<40s} {count:10d}")
+
+ def run(self, input_file: str) -> None:
+ """Run the session."""
+ self.session = perf.session(perf.data(input_file), sample=self.process_event)
+ self.session.process_events()
+ self.print_totals()
+
+def main() -> None:
+ """Main function."""
+ parser = argparse.ArgumentParser(description="Trace wakeup latency")
+ parser.add_argument("-i", "--input", default="perf.data", help="Input file")
+ args = parser.parse_args()
+
+ analyzer = WakeupLatency()
+ try:
+ analyzer.run(args.input)
+ except IOError as e:
+ print(e, file=sys.stderr)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/perf/tests/shell/test_wakeup_latency_python.sh b/tools/perf/tests/shell/test_wakeup_latency_python.sh
new file mode 100755
index 000000000000..d68c9b31d6ed
--- /dev/null
+++ b/tools/perf/tests/shell/test_wakeup_latency_python.sh
@@ -0,0 +1,83 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+# wakeup-latency python test
+
+set -e
+
+shelldir=$(dirname "$0")
+# shellcheck source=lib/setup_python.sh
+. "${shelldir}"/lib/setup_python.sh
+
+if ! "$PYTHON" -c 'import perf' > /dev/null 2>&1; then
+ echo "Skipping test, perf python module not found"
+ exit 2
+fi
+
+if ! perf check feature -q libtraceevent; then
+ echo "Skipping test, libtraceevent is disabled"
+ exit 2
+fi
+
+script_dir="$(dirname "$0")/../../python"
+script_path="${script_dir}/wakeup-latency.py"
+
+if [ ! -f "$script_path" ]; then
+ echo "Skipping test, wakeup-latency.py not found at $script_path"
+ exit 2
+fi
+
+err=0
+temp_data=""
+temp_out=""
+
+cleanup() {
+ rm -f "${temp_data}" "${temp_out}"
+}
+trap 'cleanup' EXIT TERM INT
+
+temp_data=$(mktemp /tmp/perf.data.XXXXXX)
+temp_out=$(mktemp /tmp/perf.out.XXXXXX)
+
+echo "Testing wakeup-latency.py..."
+
+# Create a perf.data file. Try to get tracepoint data.
+if perf list | grep -q "sched:sched_wakeup"; then
+ ev="sched:sched_wakeup,sched:sched_wakeup_new,sched:sched_switch"
+ perf record -e "$ev" -a -o "${temp_data}" \
+ -- sleep 0.1 >/dev/null 2>&1 || \
+ { echo "Skipping test, perf record failed"; exit 2; }
+else
+ echo "Skipping test, no sched:sched_wakeup event"
+ exit 2
+fi
+
+
+if [ ! -s "${temp_data}" ]; then
+ echo "Skipping test, perf record failed to create data"
+ exit 2
+fi
+
+# Check that the script executes
+if ! "$PYTHON" "$script_path" -i "${temp_data}" > "${temp_out}"; then
+ echo "wakeup-latency.py test failed"
+ err=1
+else
+ if ! grep -E -q "avg_wakeup_latency.*[0-9]+" "${temp_out}"; then
+ echo "Failed to find metric data rows"
+ err=1
+ else
+ echo "wakeup-latency test passed."
+ fi
+fi
+
+# Also test zero-wakeups / unhandled events path to verify division-by-zero protection
+if perf record -e cycles -o "${temp_data}" -- perf test -w noploop >/dev/null 2>&1; then
+ if ! "$PYTHON" "$script_path" -i "${temp_data}" > "${temp_out}" || \
+ ! grep -q "avg_wakeup_latency (ns): N/A" "${temp_out}"; then
+ echo "wakeup-latency zero-wakeups guard test failed"
+ err=1
+ fi
+fi
+rm -f "${temp_out}"
+
+exit $err
--
2.55.0.1082.g2b9226bbc0-goog