我需要在 .NET 应用程序中访问非常精确的计时。
我需要微秒级精度。
有没有在 .NET 中执行此操作的简单方法?
最佳答案
System.Diagnostics.Stopwatch是适合您的时间粒度的类,但请确保您使用 Stopwatch 对象的 Elapsed.Ticks
属性而不是它的 ElapsedTicks
属性(property),因为它们是两个不同的东西。
ElapsedTicks
(without the dot) refers to the number of ticks of the Stopwatch, and thus needs to be used in concert withStopwatch.Frequency
(which is not the same on all machines) to calculate the elapsed time.Elapsed.Ticks
(with the dot) gives the number ofTimespan
ticks, and is not dependent on the Stopwatch frequency.
这可能是 .Net 中最微妙的潜在错误之一。
此外,请注意,秒表 是高度精细的,但不一定准确(取决于您对该术语的定义)。 Stopwatch 返回的耗时往往会偏离系统时间。
On my laptop, Stopwatch runs almost 5 seconds ahead over 24 hours, and this effect is even worse on some other machines.
当然,如果您要计时较短的持续时间,则此效果根本无关紧要。
关于.net - .NET 中的精确时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562850/