views:

75

answers:

4

i need to calculte the time taken to execute each thread.. so i used this code to do it.

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;

string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds);
Console.WriteLine(elapsedTime, "RunTime");

now my each thread execute a method work(), this is how it goes

void work(){
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    //codes,,,

    stopWatch.Stop();

    TimeSpan ts = stopWatch.Elapsed;
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds);
    Console.WriteLine(elapsedTime, "RunTime");
}

so now my question is do i need to create an array of 1000 stopwatch objects... or not... because say 1000 work() methods are running concurrently

+2  A: 

Your code will work fine as it is, assuming each call is done on a different thread, as you are creating a new StopWatch object per thread.

That is, each StopWatch is not a shared resource, so the different threads should not be interfering with other thread StopWatch objects.

Oded
okay.. thanks a lot
phen
+1  A: 

If each work() method is spawned in its own thread, then yes.

On a side note, you probably shouldn't instantiate 1000 threads unless you have a really large server farm.

Alex
How would having a server farm help? The threads would still be local to the process...
Jon Skeet
okay.. thanks a lot
phen
A: 

Your stopWatch variable is a local variable within the work method. That means you'll have an independent variable for each time work is called... heck, you could even call work within work (in the same thread) and get independent StopWatch instances and stopWatch variables.

Jon Skeet
okay.. thanks a lot
phen
+1  A: 

Be aware that StopWatch measures "Wall Time", i.e. te time that passes in "real life" between Start and Stop. When you have multiple threads running concurrently, the time will include times where the thread didn't execute but had to wait for a CPU core to become available.

GetThreadTimes can measure time spent in a thread, but it isn't perfect either: it has a very coarse granularity (10..15ms), which makes it unsuitable for small-scale performance measurement, and gives incorrect results for threads that voluntarily give up their quantum early.

peterchen