Archive for November, 2012

Get CPU Usage of a Process using C#

This was a fun assignment. I was asked to write a piece of code that when a particular process id was passed to it it would return its CPU usage. WMI is fun. Have a great night….

public static decimal GetUssage(string pid)
{
//get the process
ManagementObjectSearcher searcher = new ManagementObjectSearcher(“SELECT * FROM Win32_Process WHERE ProcessID = ” + pid);
decimal PercentProcessorTime = 0;
foreach (ManagementObject queryObj in searcher.Get())
{
DateTime firstSample, secondSample;

//populate the process info
firstSample = DateTime.Now;
queryObj.Get();
//get cpu usage
ulong u_oldCPU = (ulong)queryObj.Properties[“UserModeTime”].Value
+ (ulong)queryObj.Properties[“KernelModeTime”].Value;
//sleep to create interval
System.Threading.Thread.Sleep(1000);
//refresh object
secondSample = DateTime.Now;
queryObj.Get();
//get new usage
ulong u_newCPU = (ulong)queryObj.Properties[“UserModeTime”].Value
+ (ulong)queryObj.Properties[“KernelModeTime”].Value;

decimal msPassed = (decimal)(secondSample – firstSample).TotalMilliseconds;

//formula to get CPU ussage
if (u_newCPU > u_oldCPU)
PercentProcessorTime = (decimal)((u_newCPU – u_oldCPU)
/ (msPassed * 100 * Environment.ProcessorCount));

Console.WriteLine(“processor time ” + PercentProcessorTime);
}
return PercentProcessorTime;
}

, , , ,

Leave a comment