Are Timers and Loops in .Net accurate?

1) Don’t use DateTime.Now for performance measurements, use StopWatch.

2) “OUTPUT: Should be same, but ..

Why should they? You are running managed/JIT’ed code on a non RTOS (real time operating system). You’re code can get bounced at any time if the OS feels like it. What lead you to believe that running the same code N times in this environment should always produce the same results to such a small degree?

3) Timers on Windows have a ~15ms resolution. Your best bet for very accurate timings is the HighPerformanceTimer API on systems (CPU’s) which support it. You haven’t even shown us the timer’s interval.

You’re failing to consider many variables here and you’re basing your predictions upon faulty assumptions. How many times are you even measuring this code? Are you taking into account the time needed to compile it the first time through? Are you running in release mode? Through VS? Are there many tasks running in the background? I could go on.

Leave a Comment