问题
I found a good question for measuring function performance, and the answers recommend to use Stopwatch as follows
Stopwatch sw = new Stopwatch();
sw.Start();
//DoWork
sw.Stop();
//take sw.Elapsed
But is this valid if you are running under multi processors machine? the thread can be switched to another processor, can it? Also the same thing should be in Enviroment.TickCount. If the answer is yes should I wrap my code inside BeginThreadAffinity as follows
Thread.BeginThreadAffinity();
Stopwatch sw = new Stopwatch();
sw.Start();
//DoWork
sw.Stop();
//take sw.Elapsed
Thread.EndThreadAffinity();
P.S
The switching can occur over the thread level not only the processor level, for example if the function is running in another thread so the system can switch it to another processor, if that happens, will the Stopwatch be valid after this switching?
I am not using Stopwatch for perfromance measurement only but also to simulate timer function using Thread.Sleep (to prevent call overlapping)
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/1149485/best-practice-for-stopwatch-in-multi-processors-machine