The following script will display instantaneous system usage percent once per second. This is usually a little higher than the figure displayed by the Task Manager which does some smoothing of the instantaneous values:
#! perl -slw
use strict;
use Win32::API::Prototype;
ApiLink(
'kernel32', q[
BOOL GetSystemTimes(
LPFILETIME lpIdleTime,
LPFILETIME lpKernelTime,
LPFILETIME lpUserTime
)
]
) or die $^E;
sub SystemTimes {
my( $idleTicks, $kernelTicks, $userTicks ) =( chr( 0 ) x 8 ) x 3;
GetSystemTimes( $idleTicks, $kernelTicks, $userTicks ) or die $^E
+;
return map{
my( $lo, $hi ) = unpack 'VV', $_;
( $hi * 2**32 + $lo );
} $idleTicks, $kernelTicks, $userTicks;
}
use constant { IDLE=>0, KERNEL=>1, USER=>2 };
$|=1;
my @last = SystemTimes;
while( sleep 1 ) {
my @now = SystemTimes;
my @deltas = map{ $now[ $_ ] - $last[ $_ ] } IDLE, KERNEL, USER;
my $busy = $deltas[ KERNEL ] + $deltas[ USER ];
my $pcUsage = ( $busy - $deltas[ IDLE ] )* 100 /( $deltas[ IDLE ]
+|| 100e5 );
printf "\rCPU usage(%%): %6.3f ", $pcUsage;
@last = @now;
}
__END__
C:\test>SysTimes.pl
CPU usage(%): 25.490
However, this is still the wrong approach to solving your problem. Imagine that your sleep times out, and you obtain the cpu usage value just as your browser is downloading a large image. At that instance, your cpu usage might be 100%, so your program will decide the system is too busy and go back to sleep for 20 seconds.
However, the user spends that 20 seconds looking at the exsquisite curves and fine detail of the bodyform shown in the image he just loaded (a Ferrari F430 Spyder say :), and so for those twenty seconds the cpu is essentially idle, and your process is sleeping, while the user is studying.
Your process wakes up just as the user zooms the image for a closeup of the air intake. Again the instantaneous cpu usage is at or close to 100%, so your process goes back to sleep. And the next 20 seconds or so the cpu is again idle whilst the user studies the screen.
The correct way to do this is by using SetPriorityClass() on your process and setting it to IDLE_PRIORITY_CLASS. That will allow your process to use upto 100% of the cpu when nothing else is using the cpu, but will never slow any other processes down by preventing them from access. It's far more accurate than anything than you could code yourself; it will avoid imposing calculation overhead upon the system as the scheduler already has all the information it needs available to it; and it is just much easier.
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|