views:

26

answers:

2

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
This looks perfect. On my system the `Frequency` field claims a resolution of better than one tenth of a microsecond.
pauldoo
A: 

Have a look at Stopwatch Class and Stopwatch.Frequency Field

astander