Water Cooler v2 Water Cooler v2 - 4 months ago 18
C# Question

System.Diagostics.Stopwatch appears not to display the correct amount of time elapsed

I am using

to time two separate operations in my program.

The program finds all prime numbers till a number input by the user.

When I give it a large input such as 100,000, it reports to have completed each of the two operations in 3 milliseconds each. I know that the algorithms I have written is quite efficient but I doubt it takes only 3 milliseconds.

Sometimes, it takes a long time for each of the two operations but still prints only a very small number of milliseconds as the time elapsed.

This has made me suspicious of something wrong in my profiling code. Could you please tell me if the stopwatch is reporting the right time elapsed? And if it is, why is it that I sometimes see the profiler output appear only after quite a lot of time?

enter image description here

enter image description here


Since FindPrimesTill only builds "query" (IEnumerable) and this query is executed only when primesTillN.Count() called, you should move stopwatch.Stop() after primesTillN.Count() and you'll get right results.