是DateTime.Now是衡量函数性能的最好方法吗? [英] Is DateTime.Now the best way to measure a function's performance?
问题描述
以下代码片段是衡量效果的最佳方式?
我需要找到一个瓶颈,并需要准确地测量时间。
DateTime startTime = DateTime.Now;
//某些执行过程
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
不,不是。使用秒表(在 System.Diagnostics
)
秒表sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();
Console.WriteLine(Time taken:{0} ms,sw.Elapsed.TotalMilliseconds);
秒表自动检查是否存在高精度计时器。
$值得一提的是,$ code> DateTime.Now 通常比
DateTime.UtcNow
由于需要完成时区的工作, DST 等。 DateTime.UtcNow通常的分辨率为15 ms。请参阅约翰·查普曼的博客帖子关于 DateTime.Now
精确的一个伟大的摘要。
有趣的琐事:秒表退回 DateTime.UtcNow
如果您的硬件不支持高频计数器。您可以通过查看静态字段 Stopwatch.IsHighResolution 。
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);
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 typically has a resolution of 15 ms. See John Chapman's blog post about DateTime.Now
precision for a great summary.
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是衡量函数性能的最好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!