是DateTime.Now衡量一个函数性能的最佳方式是什么? [英] Is DateTime.Now the best way to measure a function's performance?

查看:185
本文介绍了是DateTime.Now衡量一个函数性能的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一个瓶颈,需要准确地测量时间。

在以下code片段来衡量性能的最佳方法是什么?

 日期时间的startTime = DateTime.Now;

//一些执行过程

日期时间endTime的= DateTime.Now;
时间跨度totalTimeTaken = endTime.Subtract(startTime时);
 

解决方案

没有,不是这样的。使用秒表(在 System.Diagnostics程序

 秒表SW = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine(所用时间:{0}毫秒,sw.Elapsed.TotalMilliseconds);
 

秒表自动检查的高precision定时器的存在。

值得一提的是, DateTime.Now 往往比 DateTime.UtcNow 慢得多,由于的工作,必须与时区进行, DST 并等。

DateTime.UtcNow通常有15 NBSP的决议;毫秒。请参见约翰·查普曼的博客文章有关日期时间。现在 precision为一个伟大的总结。

有趣的花絮:秒表倒在 DateTime.UtcNow 如果你的硬件不支持高频率计数器。您可以检查,看看是否秒表使用硬件通过查看静态字段<一个实现高precision href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx">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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆