views:

331

answers:

4

Say I have a method Foo() and I want to measure the time in milliseconds it took to execute which type of Windows Performance Counter should I be using?

var stopwatch = new Stopwatch();
stopwatch.Start();
Foo();
stopwatch.Stop();
counter.RawValue = stopwatch.TotalMilliseonds;

Currently I'm using NumberOfItems64 but that persists the last value of the counter unless the new operation is performed. Is it desirable? Or should the counter go to zero as soon as the operation is done? Which counter type would you choose in this situation and why?

+1  A: 

I normally use Stopwatch, but I have also used p/invoke to kernel32.dll:

  [DllImport("Kernel32.dll")]
  private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

  [DllImport("Kernel32.dll")]
  private static extern bool QueryPerformanceFrequency(out long lpFrequency);

I have two methods called Start() and Stop():

  public void Start()
  {
     Thread.Sleep(0);
     QueryPerformanceCounter(out startTime);
  }


  public void Stop()
  {
     QueryPerformanceCounter(out stopTime);
  }

To query the duration between calls to Start() and Stop():

  public double Duration
  {
     get
     {
        return (double)(stopTime - startTime)*1000 / (double)freq;
     }
  }

Note that freq is determined in the constructor:

  public PerformanceTimer()
  {
     startTime = 0;
     stopTime = 0;

     if (QueryPerformanceFrequency(out freq) == false)
     {
        // not supported
        throw new Win32Exception();
     }
  }

For my needs, I have not noticed much of a difference, although I suggest you try both to see what suits you.

Edit: I was able to locate the original code from MSDN. It appears there are some improvements made since .Net 1.1. The take-home message is that Microsoft claims that this method provides nanosecond accuracy.

Charlie Salts
A: 

To add to previous answer, there is a very good article on both pre-made and custom-made performance counters on CodeProject..

Laurent Etiemble
+2  A: 

This sounds like a good candidate for AverageTimer32. See this SO answer for more details.

Mark Seemann
Though i dont want to average out the time across different calls.
Hasan Khan
You can't really meaningfully do much else, because what would you record for concurrent requests?
Mark Seemann
A: 

An answer and a question:

Answer: Low-tech works for me. You want microseconds? Loop it 10^6 times and use your watch.

Question: Are you asking because you want to make your code faster? Then consider this.

Mike Dunlavey