When multiple processes are running on a single CPU system, context switches often happen between them.
Here is a simple D script which can be used with DTrace to collect some information related to which process is on the CPU during a time interval:
#pragma D option quiet
sysinfo:::pswitch
{
/* who got the CPU */
printf("\n%s got the CPU", execname); /* execname is a DTrace 'In-Built' variable whose value is the currently executing process */
}
Watching it in action:
Save the above file to- whogotthecpu.d, and run it using:
# dtrace -s whogotthecpu.d
You should see the output like this:
dtrace got the CPU kdeinit got the CPU sched got the CPU sched got the CPU dtrace got the CPU kdeinit got the CPU sched got the CPU sched got the CPU kdeinit got the CPU sched got the CPU sched got the CPU kdeinit got the CPU sched got the CPU kdeinit got the CPU Xorg got the CPU sched got the CPU sched got the CPU sched got the CPU sched got the CPU kdeinit got the CPU sched got the CPU Xorg got the CPU sched got the CPU fsflush got the CPU . .
How does it work?
- We make use the sysinfo probe provider, which has a probe by the name 'pswitch' which is triggered whenever a process switch happens on the CPU. This is indicated by the line:
sysinfo:::pswitch
- When the probe is fired, we simply print the name of the process.
How many times?
Let us now add a line to the script so that it also tells us the number of times each process got the CPU.
We do this by making use of a DTrace aggregate- count(). We simply add this line:
@[execname]=count()to the script. The script should now look like this:
#pragma D option quiet
sysinfo:::pswitch
{
/* who got the CPU */
printf("\n%s got the CPU", execname);
/*.. and how many times? */
@[execname]=count()
}
Run it as earlier, and you should see output similar to this:
. . . . dtrace got the CPU kdeinit got the CPU sched got the CPU sched got the CPU dtrace got the CPU kdeinit got the CPU sched got the CPU sched got the CPU kdeinit got the CPU sched got the CPU sched got the CPU kdeinit got the CPU sched got the CPU kdeinit got the CPU Xorg got the CPU sched got the CPU sched got the CPU sched got the CPU sched got the CPU kdeinit got the CPU sched got the CPU Xorg got the CPU sched got the CPU fsflush got the CPU devfsadm got the CPU sched got the CPU Xorg got the CPU kdeinit got the CPU sched got the CPU kdeinit got the CPU korgac 1 kpdf 1 devfsadm 2 kwrapper 2 nscd 2 fsflush 3 dtrace 6 Xorg 24 kdeinit 40 sched 150For learning about DTrace, visit these links boomarked at http://delicious.com/amitkumarsaha/dtrace


