Stopwatch for performance testing

c#, performance-testing, stopwatch

Solution

If you got 0 ElapsedMicroseconds, that means that the interval is shorter than 1 ms. You may try measuring periods in Ticks and use Frequency:

  Stopwatch watch = Stopwatch.StartNew();
  ...
  // Estimated code here 
  ...
  watch.Stop();

  // Microseconds
  int microSeconds = (int)(watch.ElapsedTicks * 1.0e6 / Stopwatch.Frequency + 0.4999);
  // Nanoseconds (estimation)
  int nanoSeconds = (int)(watch.ElapsedTicks * 1.0e9 / Stopwatch.Frequency + 0.4999);

Problem

For some private project I use `Stopwatch` for performance measurement. But on low repitition count of calls I want to measure, I end up with 0 `ElapsedMilliseconds`, which makes it difficult to calculate an average. I thought about writing my own Stopwatch class. It could calculate with ticks and give a vague `ElapsedMicroseconds` based on `Stopwatch.ElapsedTicks` and `TimeSpan.TicksPerMillisecond`. This will probably be not a very good way. I definitly need something that is backed up by the high performance counters of winapi, so datetime and such will not suffice. Are there any other ideas?

Original source

Related problems