mld has asked for the wisdom of the Perl Monks concerning the following question:

I want to calculate CPU Usage of aprticular process.I have calculated Memory USage and CPU Time

use Win32::Process::Info; my $pi = Win32::Process::Info->new(); my @process_information = $pi->GetProcInfo(1333); while(1){ foreach $info (@process_information) { foreach my $key (keys %{$info}) { if ($key eq "WorkingSetSize") { $value_Mem = ${$info}{$key}/1024; print "$key:=>$value_Mem \t" } if ($key eq "KernelModeTime") { $value_Ker=${$info}{$key}; print "$key:=$value_Ker \t" } if ($key eq "UserModeTime") { $value_User=${$info}{$key}; print "$key:=$value_User \t" } } $value_CPU=$value_Ker+$value_User; $value_CPU=$value_CPU/10000000; print "CPU Time :=$value_CPU\t"; print "\n" } }

In the code I have passed the process ID.Since the process id changes I want to pass the process name.Is this possible

Replies are listed 'Best First'.
Re: How to calculate CPU Usage
by kennethk (Abbot) on May 05, 2009 at 14:24 UTC
    From the Win32::Process::Info documentation:

    @pids = $pi->ListPids (); This method lists all known process IDs in the system. If called in scalar context, it returns a reference to the list of PIDs. If you pass in a list of pids, the return will be the intersection of the argument list and the actual PIDs in the system. @info = $pi->GetProcInfo (); This method returns a list of anonymous hashes, each containing information on one process. If no arguments are passed, the list represents all processes in the system. You can pass a list of process IDs, and get out a list of the attributes of all such processes that actually exist. If you call this method in scalar context, you get a reference to the list. What keys are available depends on the variant in use. You can hope to get at least the following keys for a "normal" process (i.e. not the idle process, which is PID 0, nor the system, which is some small indeterminate PID) to which you have access: CreationDate ExecutablePath KernelModeTime MaximumWorkingSetSize MinimumWorkingSetSize Name (generally the name of the executable file) ProcessId UserModeTime

    So you can use ListPids to get a list of all process id's and use GetProcInfo to associate each process id with a name.

Re: How to calculate CPU Usage
by BrowserUk (Patriarch) on May 05, 2009 at 17:40 UTC