views:

263

answers:

3

Hi,

I have a benchmarking program that calculates the time (in milliseconds and ticks), for a persistance to Entity Framework 4.0. Is there a way to calculate CPU load ? I am guessing that I would need to query Windows to find out my CPU frequency, how many cores, etc. Does this sound right ? If so, what part of the .NET framework relates to querying the system ? I am guessing System.Diagnostics ?

Thanks,

Scott

+3  A: 

You can use a PerformanceCounter (for the System load).

Or, better:

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

You will have to relate that to wall-time to get a percentage. Also see UserProcessorTime.


Edit:

On second thought, if you want to benchmark wouldn't you rather measure just elapsed time from executing a piece of code, eg the System.Diagnostics.Stopwatch class?

Henk Holterman
You would think that the total processor time spent in the process would get successively larger as the loop executes, but sometimes a LATER operation shows less total time the an earlier one! What's the reason for that ?
Scott Davies
@Scott, I cannot reproduce that. Check the basics, like TimeSpan.__Total__Milliseconds (not Milliseconds).
Henk Holterman
+2  A: 

You can get at the Performance Counters data, but it's surely got to be better to use a profiling tool. CPU utilisation isn't in itself 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.

Neil Barnwell
+2  A: 

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

Seems to be what you're looking for

This code I found may 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);
}
Timothy Baldridge
+1 because no one uses perf mon but it is so very awesome. There are TONS of stuff to monitor.
Tony