What is the most convenient way of accurately measuring elapsed wall clock time in .NET? I'm looking for something with microsecond accuracy if possible (10^-6 seconds).
+2
A:
System.Diagnostics.Stopwatch
is your best bet. However, the exact accuracy will depend on the hardware on the computer you're using, i.e. whether a high-resolution performance counter is available. (You can check that with the IsHighResolution
field.)
Sample use:
Stopwatch sw = Stopwatch.StartNew();
// Do stuff here
sw.Stop();
TimeSpan time = sw.Elapsed;
Note that if you use the ElapsedTicks
property, that's measured in timer ticks which is not the same as the ticks used in DateTime
and TimeSpan
. That's caught me out before now - which is why I always use ElapsedMilliseconds
or the Elapsed
property.
Jon Skeet
2010-09-24 08:58:48
This looks perfect. On my system the `Frequency` field claims a resolution of better than one tenth of a microsecond.
pauldoo
2010-09-24 09:20:54