Question

I am using the wmi client for linux. Through it you can execute WQL to query windows servers remotely.

For Example;

 Select * from Win32_ComputerSystem

What I am trying to do is calculate the CPU percentage used.

I've been getting the value of 'PercentProcessorTime' from 'Win32_PerfFormattedData_Counters_ProcessorInformation'. I think this is working fine for computers with a single CPU, but I'm lost as to how to calculate the CPU usage for computers with multiple CPU's.

any help is very much appreciated.

cheers.

Was it helpful?

Solution

If you SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation then you will get a list of result sets. The first set is the overall values for all CPUs, and the rest are values for the individual CPUs.

This code shows the idea. Note that you should replace SYSTEM with the name of the computer you want to query.

use strict;
use warnings;

use Win32::OLE;
use Win32::OLE::Variant;

STDOUT->autoflush;

my $wmi = Win32::OLE->GetObject('winmgmts:\\\\SYSTEM\root\cimv2') or die Win32::OLE->LastError;
my $list = $wmi->ExecQuery('SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation');
my $n = 0;
for my $cpu (in $list) {
  printf "%s: %d%%\n", $n ? "CPU$n" : ' ALL', $cpu->PercentProcessorTime;
  $n++;
}

output

 ALL: 8%
CPU1: 8%
CPU2: 12%
CPU3: 6%
CPU4: 12%
CPU5: 6%
CPU6: 6%
CPU7: 6%
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top