.NET 中的精确时间
我需要在 .NET 应用程序中访问非常精确的计时。
我需要微秒精度。
在 .NET 中是否有一种简单的方法可以做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我需要在 .NET 应用程序中访问非常精确的计时。
我需要微秒精度。
在 .NET 中是否有一种简单的方法可以做到这一点?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
System.Diagnostics.Stopwatch 是适合此目的的类计时的粒度,但请确保使用 Stopwatch 对象的
Elapsed.Ticks
属性而不是其ElapsedTicks
属性,因为它们是两个不同的东西。这可能是 .Net 中最微妙的潜在错误之一。
另外,请注意,秒表是高度精细的,但它不一定准确(取决于您对该术语的定义)。秒表返回的经过时间往往会偏离系统时间。
当然,如果您计时的持续时间较短,则这种效果根本不重要。
System.Diagnostics.Stopwatch is the right class for this degree of granularity in your timing, but make sure you use your Stopwatch object's
Elapsed.Ticks
property instead of itsElapsedTicks
property, as they are two different things.This is probably one of the subtlest potential errors in .Net.
Also, beware that Stopwatch is highly granular, but it isn't necessarily all that accurate (depending on your definition of the term). The elapsed time returned by Stopwatch will tend to drift away from the system time.
If you're timing short durations, of course, this effect should not matter much at all.
秒表
类是您可以获得的最佳精度,它使用高频定时器。秒表的频率取决于CPU的频率,但通常在每秒数百万次范围内。
如果CPU不提供高频定时器,那么该类将回退到每秒100-50次的系统定时器。
The
Stopwatch
class is the best precision that you can get, it uses the high frequency timer.The frequency of the stopwatch depends upon the frequency of the CPU, but its usually in the millions times per second range.
If the CPU doesn't provide high frequency timer, then the class will fallback to system timer which is in the range 100-50 times per second.
使用 Stopwatch 类,应该可以解决问题。
Use the Stopwatch class, should do the trick.
Stopwatch 类由于其准确性而成为您的最佳选择:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
示例:
https://web.archive.org/web/1/http://articles. techrepublic%2ecom%2ecom/5100-10878_11-6167361.html
The Stopwatch class is your best option due to it's accuracy:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
Example:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6167361.html
除了 System.Diagnostics.StopWatch 还要检查此链接:.NET Framework 的多媒体计时器。华泰
Besides System.Diagnostics.StopWatch also check this link: The Multimedia Timer for the .NET Framework. HTH
我发现了一种方法,它比 StopWatch、PerformanceCounters 和我遇到的所有其他实现稍微更精确,并且不需要 Platform Invoke 或其他方式。
请参阅https://stackoverflow.com/questions/15725711/obtaining-microsecond - precision-using-net-without-platform-invoke
如果您发现其他情况,请告诉我!
I have found a method which works slightly more precisely then StopWatch, PerformanceCounters and every other implementation I come across and does not require Platform Invoke or otherwise.
See https://stackoverflow.com/questions/15725711/obtaining-microsecond-precision-using-net-without-platform-invoke
Let me know if you find otherwise!