Skip to content

Instantly share code, notes, and snippets.

@samueleresca
Last active December 10, 2024 16:28
Show Gist options
  • Save samueleresca/f5efa6e8c21d155c684a1cbb309f0774 to your computer and use it in GitHub Desktop.
Save samueleresca/f5efa6e8c21d155c684a1cbb309f0774 to your computer and use it in GitHub Desktop.
#!/usr/bin/bpftrace
#include <linux/sched.h>
tracepoint:sched:sched_switch
{
$prev_pid = args->prev_pid;
$next_pid = args->next_pid;
$prev_state = args->prev_state;
// Record on-CPU time for previous task
if (has_key(@start, $prev_pid))
{
@cpu[comm, $prev_pid] = sum(nsecs - @start[$prev_pid]);
}
// Start timing for next thread
@start[$next_pid] = nsecs;
// Calculate run queue time when thread gets scheduled
if (has_key(@wakeup_ts, $next_pid))
{
@runq[comm, $next_pid] = sum(nsecs - @wakeup_ts[$next_pid]);
delete(@wakeup_ts, $next_pid);
}
// Store sleep state for previous task
// in case it is not TASK_RUNNING
if ($prev_state > 0)
{
@sleeping_ts[$prev_pid] = nsecs;
@sleeping_state[$prev_pid] = $prev_state;
}
}
tracepoint:sched:sched_wakeup,
tracepoint:sched:sched_wakeup_new
{
// Track wakeup time
@wakeup_ts[tid] = nsecs;
// If thread was sleeping, record sleep time
if (has_key(@sleeping_state, tid))
{
$state = @sleeping_state[tid];
$delta = nsecs - @sleeping_ts[tid];
// Categorize based on linux thread state
if ($state & TASK_UNINTERRUPTIBLE)
{
@usl[comm, tid] = sum($delta);
}
else if ($state & TASK_INTERRUPTIBLE)
{
@slp[comm, tid] = sum($delta);
}
else if ($state & TASK_STOPPED)
{
@sus[comm, tid] = sum($delta);
}
else if ($state & TASK_DEAD)
{
@dea[comm, tid] = sum($delta);
}
delete(@sleeping_ts, tid);
delete(@sleeping_state, tid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment