xref: /aosp_15_r20/external/bcc/examples/tracing/sync_timing.py (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1#!/usr/bin/python
2#
3# sync_timing.py    Trace time between syncs.
4#                   For Linux, uses BCC, eBPF. Embedded C.
5#
6# Written as a basic example of tracing time between events.
7#
8# Copyright 2016 Netflix, Inc.
9# Licensed under the Apache License, Version 2.0 (the "License")
10
11from __future__ import print_function
12from bcc import BPF
13from bcc.utils import printb
14
15# load BPF program
16b = BPF(text="""
17#include <uapi/linux/ptrace.h>
18
19BPF_HASH(last);
20
21int do_trace(struct pt_regs *ctx) {
22    u64 ts, *tsp, delta, key = 0;
23
24    // attempt to read stored timestamp
25    tsp = last.lookup(&key);
26    if (tsp != NULL) {
27        delta = bpf_ktime_get_ns() - *tsp;
28        if (delta < 1000000000) {
29            // output if time is less than 1 second
30            bpf_trace_printk("%d\\n", delta / 1000000);
31        }
32        last.delete(&key);
33    }
34
35    // update stored timestamp
36    ts = bpf_ktime_get_ns();
37    last.update(&key, &ts);
38    return 0;
39}
40""")
41
42b.attach_kprobe(event=b.get_syscall_fnname("sync"), fn_name="do_trace")
43print("Tracing for quick sync's... Ctrl-C to end")
44
45# format output
46start = 0
47while 1:
48    try:
49        (task, pid, cpu, flags, ts, ms) = b.trace_fields()
50        if start == 0:
51            start = ts
52        ts = ts - start
53        printb(b"At time %.2f s: multiple syncs detected, last %s ms ago" % (ts, ms))
54    except KeyboardInterrupt:
55        exit()
56