Check out my new blog at https://shibumiware.blogspot.com

Tuesday, May 20, 2008

CPU Time

Here is a very simple way to check current CPU time on a multiprocessor box

Build a list of performance counters.  One for each processor

List<PerformanceCounter> cpuUsageList = new List<PerformanceCounter>();

for (int i = 0; i < Environment.ProcessorCount; i++)
{
    PerformanceCounter cpuUsage = new PerformanceCounter("Processor", "% Processor Time",i.ToString());
    cpuUsageList.Add(cpuUsage);
}
 
Implement a simple lookup method:
 
private bool IsAnyCpuTimeAboveThreshold(List<PerformanceCounter> cpuUsageList, double threshold)
{
    foreach (PerformanceCounter performanceCounter in cpuUsageList)
    {
        if (performanceCounter.NextValue() > threshold)
        {
            return true;
        }
    }

    return false;
}
 
Use it:
 
if (IsAnyCpuTimeAboveThreshold(cpuUsageList, 75.00))
{
    /*  Do something...  */
}

No comments :

Disclaimer

Content on this site is provided "AS IS" with no warranties and confers no rights. Additionally, all content on this site is my own personal opinion and does not represent my employer's view in any way.