Friday, April 16, 2010

Kernel and user profiling with dtrace

Just put together a short dtrace script for profiling both userland and kernel activity.

#!/usr/sbin/dtrace -s
#pragma D option quiet


profile-97
/arg1/
{
  @[pid,execname,ufunc(arg1)]=count();
}

profile-98
/arg0/
{
  @k[pid,execname,func(arg0)]=count();
}

tick-1s
{
  trunc(@,25);
  trunc(@k,25);
  printf("%5s %20s %20s %10s\n","PID","EXECNAME","FUNC","COUNT");
  printa("%5d %20s %20A %10@d\n",@);
  printa("%5d %20s %#20a %10@d\n",@k);
  trunc(@);
  trunc(@k);
}

The script samples the current pc for both user land and kernel about 100x per second. There's some risk of over counting since there's one probe for user and one probe for kernel. Every second the code prints out the top 25 user and kernel routines, broken down by pid and executable name. The output looks like:

  
  PID             EXECNAME                 FUNC                 COUNT
  556                 Xorg libpixman-1.so.0`pixman_image_unref  1
  556                 Xorg libpixman-1.so.0`pixman_fill         1
  556                 Xorg libc.so.1`memcpy                     1
    0                sched unix`dispatch_softint                1
    0                sched unix`dispatch_hardint                2
    0                sched unix`mach_cpu_idle                   91