是DateTime.Now衡量一个函数性能的最佳方式是什么?性能、一个函数、方式、DateTime

2023-09-02 10:13:40 作者:身居梦海°

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

在以下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);
 
如何使用NOW函数计算当前的日期和时间

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

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

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

有趣的花絮:秒表倒在 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.