2

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

Scott Davies
  • 3,665
  • 6
  • 31
  • 39
  • Do you need to measure the total cpu time on the system, or per process? – Sander Rijken Apr 09 '10 at 15:38
  • Hey Sander! I want the utilization for my process/thread...a performance counter for CPU load on the system would give erroneous data due to other processes running on Windows. – Scott Davies Apr 09 '10 at 15:48

3 Answers3

3

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?

H H
  • 263,252
  • 30
  • 330
  • 514
  • 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 Apr 09 '10 at 18:05
  • 1
    @Scott, I cannot reproduce that. Check the basics, like TimeSpan.__Total__Milliseconds (not Milliseconds). – H H Apr 09 '10 at 20:08
3

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
  • 10,455
  • 1
  • 44
  • 80
  • +1 because no one uses perf mon but it is so very awesome. There are TONS of stuff to monitor. – Tony Apr 09 '10 at 16:00
2

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
  • 41,080
  • 29
  • 148
  • 220