#!/usr/bin/ksh
#
# sampleproc - sample processes on the CPUs.
# Written using DTrace (Solaris 10 3/05).
#
# This program samples which process is on each CPU, at a particular
# configurable rate. This can be used as an estimate for which process
# is consuming the most CPU time.
#
# $Id: sampleproc 8 2007-08-06 05:55:26Z brendan $
#
# USAGE: sampleproc [hertz] # hit Ctrl-C to end sample
#
# FIELDS:
# PID Process ID
# COMMAND Command name
# COUNT Number of samples
# PERCENT Percent of CPU usage
#
# BASED ON: /usr/demo/dtrace/prof.d
#
# SEE ALSO:
# DTrace Guide "profile Provider" chapter (docs.oracle.com)
#
# PORTIONS: Copyright (c) 2005 Brendan Gregg.
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at Docs/cddl1.txt
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# CDDL HEADER END
#
# 09-Jun-2005 Brendan Gregg Created this.
# 09-Jul-2005 " " Last update.
### Usage
function usage
{
cat <<-END >&2
USAGE: sampleproc [hertz]
eg,
sampleproc # defaults to 100 hertz
sampleproc 1000 # 1000 hertz
END
exit 1
}
### Process arguments
if (( $# == 0 )); then
hertz=100
elif (( $# == 1 )); then
hertz=$1
if [[ "$hertz" = *[a-zA-Z]* ]]; then
print "ERROR2: $hertz hertz is invalid." >&2
exit 2
fi
if (( hertz > 5000 )); then
print "ERROR3: $hertz hertz is too fast (max 5000)." >&2
exit 3
fi
if (( hertz < 1 )); then
print "ERROR4: $hertz hertz is too low (min 1)." >&2
exit 4
fi
else
usage
fi
### Run DTrace
/usr/sbin/dtrace -n '
#pragma D option quiet
dtrace:::BEGIN
{
printf("Sampling at %d hertz... Hit Ctrl-C to end.\n",$1);
self->start = timestamp;
}
profile:::profile-$1
{
@Proc[pid, execname] = count();
@BigProc[pid, execname] = sum(1000); /* dont ask */
}
dtrace:::END
{
this->end = timestamp;
printf("%5s %-20s %10s\n", "PID", "CMD", "COUNT");
printa("%5d %-20s %10@d\n", @Proc);
normalize(@BigProc,
((`ncpus_online * $1 * (this->end - self->start))/100000000));
printf("\n%5s %-20s %10s\n", "PID", "CMD", "PERCENT");
printa("%5d %-20s %10@d\n", @BigProc);
}
' $hertz