Measuring Performance Using Stopwatch

Performance measurement of pieces of code should be done using a precise-enough time to have any value whatsoever. Just subtracting DateTime values doesn’t cut it because of the low resolution (10ms typically) of DateTime values. To prove this point, enter the following piece of code, which computes 50 factorial a number of times:

for (int j = 0; j < 10; j++){    var start = DateTime.Now;    var n = 1L;    for (int i = 2; i < 50; i++)        n *= i;    var end = DateTime.Now;    Console.WriteLine(end - start);}

Feel free to increase the outer loop’s iteration count. In any case, the output shouldn’t make much sense because some of the factorial calculations turn out to take no ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.