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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With