Reputation: 47
I need to calculate 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.
Upvotes: 0
Views: 173
Reputation: 41126
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.
Upvotes: 1
Reputation: 1503839
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.
Upvotes: 0
Reputation: 77379
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.
Upvotes: 1
Reputation: 499382
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.
Upvotes: 2