1

I was trying to "benchmark" two nearly identical loops. When I inspect them one by one the subtraction is without any hiccups, and the TimeSpan gives back the correct numbers as the TotalMilliseconds. When I benchmark the two loops together however the first subtraction gives back a number between 3 - 4 (which should be right), and the second one always gives back 0. What am I doing wrong? Thanks!

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
    }
}
masm64
  • 1,222
  • 3
  • 14
  • 31
  • Its wierd that you are getting 4 ms. Because counting to 10 should be done in few micro seconds not even 1 ms.... Unless you are running on wooden pc but still.... – M.kazem Akhgary Jan 08 '17 at 22:32
  • it is actually an i5 – masm64 Jan 08 '17 at 22:32
  • Also useful post: http://stackoverflow.com/questions/2143140/c-sharp-datetime-now-precision – Rob Jan 08 '17 at 22:36
  • See also [How to measure code performance in .NET?](http://stackoverflow.com/questions/457605/how-to-measure-code-performance-in-net) and [In .NET, which loop runs faster, 'for' or 'foreach'?](http://stackoverflow.com/questions/365615/in-net-which-loop-runs-faster-for-or-foreach). – CodeCaster Jan 08 '17 at 22:37
  • thank you, I appreciate it! – masm64 Jan 08 '17 at 22:39

2 Answers2

3

From the documentation:

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.

Community
  • 1
  • 1
Jesse Bakker
  • 2,403
  • 13
  • 25
2

Try using Stopwatch class which is specially designed for benchmarking:

  Stopwatch timer = new Stopwatch();

  timer.Start();

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

  timer.Stop();

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

Outcome (.Net 4.6 IA-64, Core i7 3.2 GHz)

  00:00:00.0000003

please, notice that the time is about 300 nano seconds

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215