Best Practise for Stopwatch in multi processors machine?

Posted by Ahmed Said on Stack Overflow See other posts from Stack Overflow or by Ahmed Said
Published on 2009-07-19T08:40:39Z Indexed on 2010/04/25 4:43 UTC
Read the original article Hit count: 424

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)

© Stack Overflow or respective owner

Related posts about c#

Related posts about multiprocessor