使用 .NET 库测量延迟
我正在用 .NET 构建一个应用程序(什么语言并不重要,重要的是框架的语言)。 我需要计算从一条指令到另一条指令所花费的时间。所以,我需要测量时间。
如何使用 .NET 库来做到这一点?哪一个是正确的命名空间/类?谢谢
I am building an application in .NET (not important what language, it is a language of the framework).
I need to count how much time passes from an instruction to another. I need, so, to measure time.
How to do this using .NET libraries? Which one is the right namespace/class to use? Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 Stopwatch 类。可以在链接的 MSDN 页面上找到示例。
Try using the Stopwatch class. An example can be found on the linked MSDN page.
System.Diagnostics.Stopwatch
可能就是您想要用于此目的的东西,但请记住,虽然Stopwatch
非常细粒度,但它并非如此在长时间内尤其准确。例如,如果您启动秒表
并让它运行正好 24 小时(通过独立时钟或计算机的系统时钟测量),它将显示 24 小时加上的经过时间 5-10 秒(不是 毫秒)。因此,如果您想测量非常短的持续时间,请使用秒表。如果您希望测量的持续时间较长(大约几分钟或更长),您应该在序列的开始和结束处调用
DateTime.UtcNow
,并计算差异作为时间跨度
。System.Diagnostics.Stopwatch
is probably what you want to use for this purpose, but keep in mind that whileStopwatch
is highly granular it is not especially accurate for long time periods. For example, if you start aStopwatch
and let it run for exactly 24 hours (as measured by an independent clock or the computer's system clock), it will show an elapsed time of 24 hours plus 5-10 seconds (not milliseconds).So, if you want to measure very short durations, use
Stopwatch
. If the durations you wish to measure are longer (on the order of a few minutes or more), you should instead make calls toDateTime.UtcNow
at the start and end of your sequence, and calculate the difference as aTimespan
.