Are Timers and Loops in .Net accurate?

后端 未结 4 520
旧巷少年郎
旧巷少年郎 2020-11-29 09:51

While developing a program to calculate the frequency and pulse width of the pulse generated by a 555 timer IC, coming to the PC via PC Parallel port. I noticed that every t

4条回答
  •  清歌不尽
    2020-11-29 10:29

    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.

提交回复
热议问题