<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl

## prints out CPU utilisation, from a top -n 1 |head -15 &gt;&gt;outfile
## 100% = cpu working its socks off.
## andyw vistorm 20061115
## this script is licensed under the GPL V2.0

# vars {{{1
my $SLEEP	= 15;
my $fname	= 'cpustats';
my $records	= 0;

open(A,$fname);
$fh = *A;

my (@cpustats, %cpus, $rn, $h, $m);
my ($r, $c, $initial_time) = get_start($fh);
my ($mode, $invert) = flags();

# report header {{{1
print "TIME,";
for(my $i=0; $i&lt;$c; $i++) { printf "cpu%02d,",$i }
print "\n";

$rn=-1;

# main loop {{{1
while(&lt;A&gt;) {
	if (/CPU/o) {
		$rn++;
		if ($rn) {

			## time header {{{2
			($h,$m) = (localtime($initial_time + ($rn) * $SLEEP))[2,1];
			## cpu dump {{{2 
			printf("%02d:%02d,",$h,$m);
			print join', ',map {
				$_=sprintf("%02d",$cpus{$_})
			} sort keys %cpus;
			print "\n";
			
		}
	}
	next unless /cpu\d+/;
	# regexp {{{2
#CPU states:  cpu    user    nice  system    irq  softirq  iowait    idle[K
 #          cpu00    2.9%    0.0%    0.0%   0.0%     0.0%   97.0%    0.0%[K
	@cpustats = 
		(m/^\s*(\S+)\s*([\d\.]+)\%\s*([\d\.]+)\%\s*([\d\.]+)\%\s*([\d\.]+)\%\s*([\d\.]+)\%\s*([\d\.]+)\%\s*([\d\.]+)\%/);
	$cpus{$cpustats[0]} = $invert ? 100 - $cpustats[$mode] : $cpustats[$mode];

}

# get_start {{{1
sub get_start {
	my $fh = shift;
	my $records = 0;
	my $cpus = 0;

	while(&lt;$fh&gt;) { 
		$records++ if /CPU states/o; 

		# figure out number of CPUs
		if (  $records &lt; 2) {
			$cpus++ if (/\s+cpu\d+\s+/o);
		}
	}
	
	seek($fh,0,0);
	return ($records, $cpus, ((stat($fname))[9] - $records * $SLEEP));
} 

# flags {{{1
sub flags {
	## defaults args - 7th column (% idle) and invert (ie invert idle = CPU used)
	return (7,1) unless scalar @ARGV;

	my ($i, $invert) = (0,0);
	my @flags = qw/-user -nice -system -irq -softirq -iowait -idle/;
	if (length $ARGV[1]) {
		if ($ARGV[1] eq '-invert') { $invert = 1; }
		else { usage() }
	}

	for ($i=0; $i &lt; scalar @flags; $i++) {
		if ($flags[$i] eq $ARGV[0]) {
			return ($i+1, $invert);
		}
	}

	usage();
}

# usage {{{1
sub usage {
	print "Usage: $0 -[user|nice|system|irq|softirq|iowait|idle] [-invert]\n";
	print "          Default is -idle -invert (ie %CPU used, by cpu)\n";
	print "          Specifying any flags overrides both of these.\n";
	exit 1;
}
# }}}

# vim: ts=4 fdm=marker
</pre></body></html>