Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopwatch for performance testing

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?

like image 727
Mare Infinitus Avatar asked Jan 13 '23 21:01

Mare Infinitus


2 Answers

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);
like image 118
Dmitry Bychenko Avatar answered Jan 24 '23 02:01

Dmitry Bychenko


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.

like image 45
Manuel Amstutz Avatar answered Jan 24 '23 03:01

Manuel Amstutz