5

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

pauldoo
  • 18,087
  • 20
  • 94
  • 116

3 Answers3

8

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
  • 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
0

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.

See https://stackoverflow.com/questions/15725711/obtaining-microsecond-precision-using-net-without-platform-invoke

For a better way IMHO

Let me know if you find otherwise!

Community
  • 1
  • 1
Jay
  • 3,276
  • 1
  • 28
  • 38
0

Have a look at Stopwatch Class and Stopwatch.Frequency Field

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284