Question

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?

Was it helpful?

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);

OTHER TIPS

StopWatch is the thing you need. Use:

double diffMs = (stopWatch.ElapsedTicks * 1000.0) / Stopwatch.Frequency;

StopWathch.ElapsedMilliseconds is defined as long. Therefore it is not possible that it is more precise than one millisecond.

C# time in microseconds

long microseconds = ticks / (TimeSpan.TicksPerMillisecond / 1000);

forgive my ignorance, (but) if it's less than a millisecond (1000 ticks), you surely don't have to diagnose it for performance issues

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top