1#!/usr/bin/env python 2# Copyright (c) PLUMgrid, Inc. 3# Licensed under the Apache License, Version 2.0 (the "License") 4 5from bcc import BPF 6from time import sleep 7 8b = BPF(text=""" 9#include <uapi/linux/ptrace.h> 10#include <linux/sched.h> 11 12struct key_t { 13 u32 prev_pid; 14 u32 curr_pid; 15}; 16// map_type, key_type, leaf_type, table_name, num_entry 17BPF_HASH(stats, struct key_t, u64, 1024); 18int count_sched(struct pt_regs *ctx, struct task_struct *prev) { 19 struct key_t key = {}; 20 u64 zero = 0, *val; 21 22 key.curr_pid = bpf_get_current_pid_tgid(); 23 key.prev_pid = prev->pid; 24 25 // could also use `stats.increment(key);` 26 val = stats.lookup_or_init(&key, &zero); 27 (*val)++; 28 return 0; 29} 30""") 31b.attach_kprobe(event="finish_task_switch", fn_name="count_sched") 32 33# generate many schedule events 34for i in range(0, 100): sleep(0.01) 35 36for k, v in b["stats"].items(): 37 print("task_switch[%5d->%5d]=%u" % (k.prev_pid, k.curr_pid, v.value)) 38