aboutsummaryrefslogtreecommitdiff
path: root/Proc/sampleproc
blob: 891be14650942d7772079933b1d0d09ffb89be11 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/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.sun.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