how can I get the CPU Usage which is the percentage of a process used CPU in Task Manager? use UserModeTime and KernelModeTime ?
That's much harder to do. At any given moment, on a single cpu machine, only one process is running, and using 100% of the cpu, whilst all other processes are idle.
Therefore, to get a %cpu usage figure you need to
As you can see, not hugely difficult, but avoiding the stats gathering process itself using a large percentage of the cpu takes care.
If the machine has multiple cpus or cores, life gets harder again.
Here's some code that works for a single cpu, though it consumes 15-20% cpu to produce figures once per second and there is not much that you can do about it. It will give distorted numbers during periods in which a new process starts or an old process finishes. It will also give erroneous results if you have multiple cpus.
#! perl -slw use strict; use warnings; use Win32::Process::Info; use List::Util qw[ sum ]; my $pi = Win32::Process::Info->new; my @pids = $pi->ListPids; my @proc_info; my @fields = qw[ Name WorkingSetSize UserModeTime KernelModeTime ]; my %byPid; while( 1 ) { my @pids = $pi->ListPids; for my $pid ( @pids ) { my @info = $pi->GetProcInfo( { no_user_info => 1 }, $pid ); for my $info ( @info ) { $byPid{ $pid }{ last } = [ @{ $info }{ @fields } ]; } } sleep 1; for my $pid ( @pids ) { my @info = $pi->GetProcInfo( { no_user_info => 1 }, $pid ); for my $info ( @info ) { $byPid{ $pid }{ current } = [ @{ $info }{ @fields } ]; } } my $totalDelta = 0; for my $pid ( @pids ) { $totalDelta += $byPid{ $pid }{ delta } = sum( @{ $byPid{ $pid }{ current } }[ 2, 3 ] ) - sum( @{ $byPid{ $pid }{ last } }[ 2, 3 ] ); } system 'cls'; print "\n pid Name memory %cpu"; for my $pid ( @pids ) { printf "%5d %20s %10u %.1f%%\n", $pid, @{ $byPid{ $pid }{ last } }[ 0, 1 ], $byPid{ $pid }{ delta } * 100 / ($totalDelta||1); } }
In reply to Re^5: How to get the Memory usage of specified Process on Windows ?
by BrowserUk
in thread How to get the Memory usage of specified Process on Windows ?
by ilovit
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |