How do you programmatically calculate the CPU load?

I have a benchmarking program that calculates the time (in milliseconds and ticks) for resilience to Entity Framework 4.0. Is there a way to calculate the CPU load? My guess is that I will need to query Windows to find out my processor frequency, number of cores, etc. Does this sound right? If so, what part of the .NET framework is related to the system request? I'm assuming System.Diagnostics?

Thank,

Scott

+2


source to share


3 answers


You can use PerformanceCounter (to boot the system).

Or, better:

var p = System.Diagnostics.Process.GetCurrentProcess();
var span = p.TotalProcessorTime;

      

You will need to link this to wall time to get the percentage. Also see UserProcessorTime.




Edit:

On the other hand, if you want to do benchmarking, wouldn't you rather just measure the elapsed time from the execution of a piece of code, such as the System.Diagnostics.Stopwatch class?

+3


source


http://msdn.microsoft.com/en-us/library/3t90y2y1(v=VS.90).aspx

It seems that you are looking for



This code I found might help:

using System.Diagnostics;
PerformanceCounter oPerf1 = new PerformanceCounter();
oPerf1.CategoryName = "Processor";
oPerf1.CounterName = "% Processor Time";
oPerf1.InstanceName = "0";
int I;
for (I = 0; (I <= 100); I++) {
    SomeListBox.Items.Add(oPerf1.NextValue);
    Threading.Thread.Sleep(20);
}

      

+3


source


You can get Performance Counters data, but it is definitely better to use a profiling tool. Processor utilization alone is not a useful measurement. You want to know which are the slowest bits of your code compared to other bits, and which are fast, but called too many times, etc.

+2


source







All Articles