blob: a00bf5a5eb7ce9bbc7fe62ac769fdee44a43d6eb [file] [log] [blame]
Alexey Ivanov777e8022019-01-03 13:46:38 -08001#!/usr/bin/env python
Brendan Gregg239e8632016-07-25 15:02:32 -07002#
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
13
14# load BPF program
15b = BPF(text="""
16#include <uapi/linux/ptrace.h>
Brendan Gregg239e8632016-07-25 15:02:32 -070017
18BPF_HASH(last);
19
Samuel Naire7a5bdc2017-08-22 23:09:55 +080020int do_trace(struct pt_regs *ctx) {
Brendan Gregg239e8632016-07-25 15:02:32 -070021 u64 ts, *tsp, delta, key = 0;
22
23 // attempt to read stored timestamp
24 tsp = last.lookup(&key);
25 if (tsp != 0) {
26 delta = bpf_ktime_get_ns() - *tsp;
27 if (delta < 1000000000) {
28 // output if time is less than 1 second
29 bpf_trace_printk("%d\\n", delta / 1000000);
30 }
31 last.delete(&key);
32 }
33
34 // update stored timestamp
35 ts = bpf_ktime_get_ns();
36 last.update(&key, &ts);
Samuel Naire7a5bdc2017-08-22 23:09:55 +080037 return 0;
Brendan Gregg239e8632016-07-25 15:02:32 -070038}
39""")
40
Yonghong Song83b49ad2018-04-24 10:15:24 -070041b.attach_kprobe(event=b.get_syscall_fnname("sync"), fn_name="do_trace")
Brendan Gregg239e8632016-07-25 15:02:32 -070042print("Tracing for quick sync's... Ctrl-C to end")
43
44# format output
45start = 0
46while 1:
47 (task, pid, cpu, flags, ts, ms) = b.trace_fields()
48 if start == 0:
49 start = ts
50 ts = ts - start
51 print("At time %.2f s: multiple syncs detected, last %s ms ago" % (ts, ms))