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).
-
2Is elapsed "wall clock time" equivalent to elapsed time? – spender Sep 24 '10 at 08:58
-
@spender: [Wall clock time](http://en.wikipedia.org/wiki/Wall_clock_time) is the total time needed to complete a task. – Dirk Vollmar Sep 24 '10 at 09:01
-
Ah. OK, as opposed to CPU time. Got it now. – spender Sep 24 '10 at 09:05
-
It comes from the notion of measuring the elapsed time using a clock hanging on the wall. It is totally oblivious to CPU time or anything else going on inside the machine. – pauldoo Sep 24 '10 at 09:22
3 Answers
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.
- 1,421,763
- 867
- 9,128
- 9,194
-
This looks perfect. On my system the `Frequency` field claims a resolution of better than one tenth of a microsecond. – pauldoo Sep 24 '10 at 09:20
Here is a class which provides waiting on this scale since I assume in the end that is what you need to do. The StopWatch @ CPU time will possibly get a APC and you will miss your end time.
For a better way IMHO
Let me know if you find otherwise!