C#TimeSpan给出0作为TotalMilliseconds


C# TimeSpan gives 0 as TotalMilliseconds

本问题已经有最佳答案,请猛点这里访问。

我试图"基准"两个几乎相同的循环。当我一个接一个地检查它们时,减法就不会打嗝,TimeSpan会返回正确的数字作为总毫秒数。然而,当我将两个循环放在一起进行基准测试时,第一个减法返回一个介于3-4之间的数字(应该是正确的),第二个总是返回0。我做错什么了?谢谢!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(":: Simple for ::");

        var a = 0;
        var start = DateTime.Now;

        for (int i = 0; i < 10; i++)
        {
            a += i;
        }

        Console.WriteLine("Elapsed time: {0} ms", (DateTime.Now - start).TotalMilliseconds); // 3 - 4 ms
        Console.WriteLine(":: Fancy for ::");

        a = 0;
        start = DateTime.Now;

        foreach (var i in Enumerable.Range(0, 9))
        {
            a += i;
        }

        Console.WriteLine("Elapsed time: {0} ms", (DateTime.Now - start).TotalMilliseconds); // 0 ms
    }
}


从文档:

The resolution of this property depends on the system timer, which is approximately 15 milliseconds on Windows systems.As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.

The Now property is frequently used to measure performance. However, because of its low resolution, it is not suitable for use as a benchmarking tool. A better alternative is to use the Stopwatch class.


尝试使用秒表类是专门设计为基准:

1
2
3
4
5
6
7
8
9
10
11
12
  Stopwatch timer = new Stopwatch();

  timer.Start();

  for (int i = 0; i < 10; i++)
  {
      a += i;
  }

  timer.Stop();

  Console.WriteLine($"Elapsed time: {timer.Elapsed}");

结果(。NET 4.6 IA-64,酷睿i7 3.2 GHz)

1
  00:00:00.0000003

请注意,这是约300纳米秒的时间