2.7.9 Exercise: Counting Context Switches on a System

Create an executable D program named cswpercpu.d that displays a timestamp and prints the number of context switches per CPU and the total for all CPUs once per second, together with the CPU number or "total".

  • Using the BEGIN probe, print a header for the display with columns labelled Timestamp, CPU, and Ncsw.

  • Using the sched:::on-cpu probe to detect the end of a context switch, use lltostr() to convert the CPU number for the context in which the probe fired to a string, and use count() to increment the aggregation variable @n once with the key value set to the CPU number string and once with the key value set to "total".

    See sched Provider in the Oracle Linux Dynamic Tracing Guide for a description of the sched:::on-cpu probe.

  • Using the profile:::tick-1sec probe, use printf() to print the data and time, use printa() to print the key (the CPU number string or "total") and the aggregation value. The date and time are available as the value of walltimestamp variable, which you can print using the %Y conversion format

  • Use clear() to reset the aggregation variable @n.

(Estimated completion time: 40 minutes)