DateTime.Now 是衡量函数性能的最佳方法吗?

Is DateTime.Now the best way to measure a function#39;s performance?(DateTime.Now 是衡量函数性能的最佳方法吗?)
本文介绍了DateTime.Now 是衡量函数性能的最佳方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一个瓶颈,并且需要尽可能准确地测量时间.

I need to find a bottleneck and need to accurately as possible measure time.

以下代码片段是衡量性能的最佳方式吗?

Is the following code snippet the best way to measure the performance?

DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);

推荐答案

不,不是.使用 秒表(在 System.Diagnostics)

No, it's not. Use the Stopwatch (in System.Diagnostics)

Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

秒表自动检查是否存在高精度计时器.

Stopwatch automatically checks for the existence of high-precision timers.

值得一提的是,由于必须处理时区,夏令时等.

It is worth mentioning that DateTime.Now often is quite a bit slower than DateTime.UtcNow due to the work that has to be done with timezones, DST and such.

DateTime.UtcNow 通常具有 15 ms 的分辨率.请参阅 John Chapman 的博文,了解 DateTime.现在精确到一个很好的总结.

DateTime.UtcNow typically has a resolution of 15 ms. See John Chapman's blog post about DateTime.Now precision for a great summary.

有趣的琐事:如果您的硬件不支持高频计数器,秒表会退回到 DateTime.UtcNow.您可以通过查看静态字段 Stopwatch.IsHighResolution.

Interesting trivia: The stopwatch falls back on DateTime.UtcNow if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field Stopwatch.IsHighResolution.

这篇关于DateTime.Now 是衡量函数性能的最佳方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)