Best Practice for Stopwatch in multi processors machine?

耗尽温柔 提交于 2019-12-03 07:54:19

If the function itself isn't multithreaded (eg it doesn't spawn other threads/processes and wait for them to complete) then the only issue is your machine.

If your machine is busy doing other things it could invalidate your test (eg encoding a H.264 video while doing a CPU-bound test). Likewise if you use all the physical memory on testing something that is memory-bound then it could invalidate your results.

So the general principle is that the machine should be under a minimal-to-normal load when conducting such tests. Other than that there isn't a multiprocessing issue. Yes, the program could swap cores while running but the overhead of doing that is either a tiny percentage of your measured time or the measured time is so small that the granularity of the system's time measurement is an issue.

I think you're asking about the low-level implementation of Stopwatch and whether switching processors in the middle of execution could invalidate the behavior. The implementation does use QueryPerformanceCounter internally (see the MS BCL Reference Sources; I've confirmed it in .NET 4.0 at least.)

The MS documentation for this API states:

On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL).

So, you are correct; in principle, it shouldn't matter, but this comment suggests there have been observed instances where the implementation does not accord with the intended interface. If you want to guarantee the correctness of the measurement, you can use thread affinity, as you stated. That said, I'm guessing any errors observed are quite small, as a large difference would be a pretty serious BIOS or HAL bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!