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 } } 
5

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.