views:

51

answers:

2

Hi,

Is there a high precision timer that I can use to benchmark the amount of time a series of operations/statements take when executing ? A timer that returns the number of seconds since epoch would be insufficient, as the resolution is in seconds.

I am thinking that the general implementation would be:

  1. Get starting time in milliseconds.
  2. Execute statements.
  3. Get ending time in milliseconds.
  4. Elapsed time = end - start.

Thanks,

Scott

+1  A: 

You might use a Stopwatch object for that, it has Start and Stop methods. However, note that it measure total time, not net time, which might be affected by the load on your system. To get net time you need to use some specialized profiling tools.

Aviad P.
Thanks for your answer! Can you elaborate on what you mean between total and net time ? I am guessing that when you mention load as a factor that the time would vary depending on load, so a better benchmark would be running this at different loads and averaging it out ? Or by using profiling tools ?
Scott Davies
Only profiling tools would provide an accurate measurement, but if you don't need high accuracy, looping over the operation a few hundred times and dividing the time by the number of iterations (i.e. averaging) - would suffice.
Aviad P.
Do profiling tools simulate varying workloads while the benchmarking is taking place ?
Scott Davies
No they don't they measure the exact number of cpu cycles spent actually running your code, so they factor out everything else.
Aviad P.
+1  A: 

The Stopwatch class works well for this. Note that it measures wall clock time, not code execution time.

    Stopwatch sw= new Stopwatch();
    sw.Start();
    DoTimeConsumingOperation();
    sw.Stop();
    Console.WriteLine(sw.Elapsed); // in milliseconds

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

Michael Petrotta
Thanks for your answer! I will implement this.
Scott Davies