Search code examples
.netmulticoreperformancecounter

How to get accurate CPU usage for a process on a multi-processor / multi-core system


Or maybe the question is more like "What am I doing blatantly wrong here?"

I have a test app which does nothing but watch its own cpu usage. It looks a little something like this:

protected PerformanceTrace()
{
   Process currentProcess = Process.GetCurrentProcess();
   this.cpuCounter = new PerformanceCounter("Process", "% Processor Time", currentProcess.ProcessName);
   this.coreCount = Environment.ProcessorCount;
}

private int coreCount;
private DateTime lastCpuRead = DateTime.MinValue;
private float _cpuUsage;
private float CpuUsage
{
   get
   {
      if ((DateTime.Now - this.lastCpuRead) > TimeSpan.FromSeconds(1.0))
      {
         this._cpuUsage = this.cpuCounter.NextValue();
      }
      return this._cpuUsage / this.coreCount;
   }
}

The CpuUsage property is read very frequently. Here's the thing:

On my machine, Environment.ProcessorCount produces a value of 2. However, the value coming from the counter is often up to 800. What I am assuming is it has something to do with multiple cores and hyperthreading. What can I do to get the actual value that I'm looking for? (The total % processor time for this particular process)


Solution

  • You are rigt - you have to divide the number from Performance Counters by the number of CPUs times the number of real threads per CPU - one per core, plus one per core if hyperthreading is a factor.

    In C# I don't know how to determine this. In native code you can use GetLogicalProcessorInformation and its associated structure to count the logical processors, including those that share a core.