views:

231

answers:

1

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)

+2  A: 

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.

cletus
if the function is running in a background thread, this means the function thread can switch to another processor that leads to error in the measurements
Ahmed Said
According to MSDN: "Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating." Ref: http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx
Tormod Fjeldskår
@Tormod Fjeldskår, foreground/background threads can be switched to other processors so I do not care about its type but I mentioned it in my comment for example not more
Ahmed Said