DateTime.Now現在是衡量函數性能的最佳方法嗎? (Is DateTime.Now the best way to measure a function's performance?)


問題描述

DateTime.Now 是衡量函數性能的最佳方法嗎? (Is DateTime.Now the best way to measure a function's performance?)

我需要找到一個瓶頸,並且需要盡可能準確地測量時間。

以下代碼片段是衡量性能的最佳方法嗎?

DateTime startTime = DateTime.Now;

// Some execution process

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

參考解法

方法 1:

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.

方法 2:

If you want something quick and dirty I would suggest using Stopwatch instead for a greater degree of precision.

Stopwatch sw = new Stopwatch();
sw.Start();
// Do Work
sw.Stop();

Console.WriteLine("Elapsed time: {0}", sw.Elapsed.TotalMilliseconds);

Alternatively, if you need something a little more sophisticated you should probably consider using a 3rd party profiler such as ANTS.

方法 3:

This article says that first of all you need to compare three alternatives, Stopwatch, DateTime.Now AND DateTime.UtcNow.

It also shows that in some cases (when performance counter doesn't exist) Stopwatch is using DateTime.UtcNow + some extra processing. Because of that it's obvious that in that case DateTime.UtcNow is the best option (because other use it + some processing)

However, as it turns out, the counter almost always exists ‑ see Explanation about high‑resolution performance counter and its existence related to .NET Stopwatch?.

Here is a performance graph. Notice how low performance cost UtcNow has compared to alternatives:

Enter image description here

The X axis is sample data size, and the Y axis is the relative time of the example.

One thing Stopwatch is better at is that it provides higher resolution time measurements. Another is its more OO nature. However, creating an OO wrapper around UtcNow can't be hard.

方法 4:

It's useful to push your benchmarking code into a utility class/method. The StopWatch class does not need to be Disposed or Stopped on error. So, the simplest code to time some action is

public partial class With
{
    public static long Benchmark(Action action)
    {
        var stopwatch = Stopwatch.StartNew();
        action();
        stopwatch.Stop();
        return stopwatch.ElapsedMilliseconds;
    }
}

Sample calling code

public void Execute(Action action)
{
    var time = With.Benchmark(action);
    log.DebugFormat(“Did action in {0} ms.”, time);
}

Here is the extension method version

public static class Extensions
{
    public static long Benchmark(this Action action)
    {
        return With.Benchmark(action);
    }
}

And sample calling code

public void Execute(Action action)
{
    var time = action.Benchmark()
    log.DebugFormat(“Did action in {0} ms.”, time);
}

方法 5:

The stopwatch functionality would be better (higher precision). I'd also recommend just downloading one of the popular profilers, though (DotTrace and ANTS are the ones I've used the most... the free trial for DotTrace is fully functional and doesn't nag like some of the others).

(by David BasarabMarkus OlssonmmcdoleValentin KuzubAnthony Mastreanjsight)

參考文件

  1. Is DateTime.Now the best way to measure a function's performance? (CC BY‑SA 2.5/3.0/4.0)

#datetime #performance #.net #timer #C#






相關問題

NHibernate:HQL:從日期字段中刪除時間部分 (NHibernate:HQL: Remove time part from date field)

如何獲得在給定時間內發送超過 X 個數據包的 IP (How do I get IPs that sent more than X packets in less than a given time)

Памылка дадання даты пры адніманні ад 0:00 (Dateadd error when subtracting from 0:00)

查找與日曆相比缺失的日期 (Find missing date as compare to calendar)

CodeReview:java Dates diff(以天為單位) (CodeReview: java Dates diff (in day resolution))

顯示兩個給定時間之間的 15 分鐘步長 (display 15-minute steps between two given times)

如何在 C# 中獲取月份名稱? (How to get the month name in C#?)

fromtimestamp() 的反義詞是什麼? (What is the opposite of fromtimestamp()?)

構建 JavaScript 時缺少模塊 (Missing Module When Building JavaScript)

setTimeout 一天中的特定時間,然後停止直到下一個特定時間 (setTimeout for specific hours of day and then stop until next specific time)

將浮點數轉換為 datatime64[ns] (Converting float into datatime64[ns])

Python Dataframe 在連接時防止重複 (Python Dataframe prevent duplicates while concating)







留言討論