#!/usr/bin/sh
#
# amd64cpi-kernel - measure kernel CPI and Utilization on AMD64 processors.
#
# USAGE: amd64cpi-kernel [interval]
#   eg,
#        amd64cpi-kernel 0.1		# for 0.1 second intervals
#
# CPI is cycles per instruction, a metric that increases due to activity
# such as main memory bus lookups.

interval=${1:-1}	# default interval, 1 second

set -- `kstat -p unix:0:system_misc:ncpus`		# assuming no psets,
cpus=$2							# number of CPUs

pics='BU_cpu_clk_unhalted,sys0'				# cycles
pics=$pics,'FR_retired_x86_instr_w_excp_intr,sys1'	# instructions

/usr/sbin/cpustat -tc $pics $interval | perl -e '
	printf "%16s %16s %8s %8s\n", "Cycles", "Instructions", "CPI", "%CPU";
	while (<>) {
		next if ++$lines == 1;
		split;
		$total += $_[3];
		$cycles += $_[4];
		$instructions += $_[5];

		if ((($lines - 1) % '$cpus') == 0) {
			printf "%16u %16u %8.2f %8.2f\n", $cycles,
			    $instructions, $cycles / $instructions, $total ?
			    100 * $cycles / $total : 0;
			$total = 0;
			$cycles = 0;
			$instructions = 0;
		}
	}
'
