PrintLogo

Monitoring Windows CPU Performance With Perl




The Win32::PerfLib module is a glorious way to extract performance data from Windows boxen. Check out this site for more information. We used perl 5.6.1. Here is a script that shows how to use this module:

use Win32::PerfLib;
$processor = 238;
$proctime = 6;
while (6 ne 9){
if(my $perflib = new Win32::PerfLib('srv-48')){
$proc_ref0 = {};
$proc_ref1 = {};
$perflib->GetObjectList($processor, $proc_ref0);
sleep 3;
$perflib->GetObjectList($processor, $proc_ref1);
sleep 3;
$perflib->Close($proc_ref0);
$perflib->Close($proc_ref1);
$instance_ref0 = $proc_ref0->{Objects}->{$processor}->{Instances};
$instance_ref1 = $proc_ref1->{Objects}->{$processor}->{Instances};
for $p (keys %{$instance_ref0}) {
$counter_ref0 = $instance_ref0->{$p}->{Counters};
$counter_ref1 = $instance_ref1->{$p}->{Counters};
for $i (keys %{$counter_ref0}) {
next if ($instance_ref0->{$p}->{Name} eq "_Total");
if($counter_ref0->{$i}->{CounterNameTitleIndex} == $proctime){
$Numerator0 = $counter_ref0->{$i}->{Counter};
$Denominator0 = $proc_ref0->{PerfTime100nSec};
$Numerator1 = $counter_ref1->{$i}->{Counter};
$Denominator1 = $proc_ref1->{PerfTime100nSec};
$proc_time{$p} = (1- (($Numerator1 - $Numerator0) /
($Denominator1 - $Denominator0 ))) * 100;
if ($highproc < $proc_time{$p}){
$highproc = $proc_time{$p};
}
}
}
}
print $highproc."\n";
$highproc=0;
}
}

Let's run the script:

C:\tm>\Perl\bin\perl cpu.pl
19.5
62.5
41.4507577867798
39.7905638112966
52.6041666666667
45.595836881521
25
41.8848050700341
4.14509679185638
5.12821135568664
^C
C:\tm>

Here is the task manager view on srv-48:



The if clause around the initial call to Perflib is necessary to keep the program from crashing when the host is unavailable. Set up an else clause to deal with this more completely.



This article comes from NetAdminTools:
http://www.netadmintools.com/

The URL for this story is:
http://www.netadmintools.com/art324.html

Copyright 1997-2008 NetAdminTools.com. Read our Terms of Use.