Accurately measure elapsed wall clock time in .NET
What is the most convenient way of accurately measuring elapsed wall clock time in .NET? I'm looking for something with microsec开发者_运维知识库ond accuracy if possible (10^-6 seconds).
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.
Have a look at Stopwatch Class and Stopwatch.Frequency Field
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!
精彩评论