准确测量.NET经过的挂钟时间 [英] Accurately measure elapsed wall clock time in .NET
问题描述
什么是精确测量经过挂钟时间在.NET中最便捷的方式是什么?我在找东西微秒精度如果可能的话(10 ^ -6秒)。
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).
推荐答案
<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx"><$c$c>System.Diagnostics.Stopwatch$c$c>是你最好的选择。然而,确切的精确度将取决于你使用,即高分辨率的性能计数器是否可在计算机上的硬件。 (您可以检查与<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx"><$c$c>IsHighResolution$c$c>场。)
使用示例:
Stopwatch sw = Stopwatch.StartNew();
// Do stuff here
sw.Stop();
TimeSpan time = sw.Elapsed;
请注意,如果你使用的<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.elapsedticks.aspx"><$c$c>ElapsedTicks$c$c>属性,在定时器的真实测量蜱这是不一样的的DateTime
使用的蜱时间跨度
。这是抓住了我之前了 - 这就是为什么我总是用<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.elapsedmilliseconds.aspx"><$c$c>ElapsedMilliseconds$c$c>或<一href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.elapsed.aspx"><$c$c>Elapsed$c$c>属性。
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.
这篇关于准确测量.NET经过的挂钟时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!