Reputation: 151
Part of my project for studies is using stopwatch to measure time.
Each stopwatch is used in different task to measure how long while loop should work.
I wonder if I put a lot of long tasks, will this measure be accurate.
Idea code sample:
public static void run(){
var tasks= new List<Task<int>>();
foreach(var task in taskList) //taskList is global object with 10 variables inside
tasks.Add(Task.Factory.StartNew<int>(()=>taskFunction(task)));
Task.WaitAll(tasks.ToArray());
}
private int taskFunction(task) {
Stopwatch watch = new Stopwatch();
while (watch.ElapsedMilliseconds < MaxTime * 1000)
{
watch.Start();
doSomething(); // takes lot of time;
watch.Stop();
doSomethingDiffrent();
}
}
So I will create like 10 tasks. If task is not calculated by processor will time in stopwatch run and waste?
Upvotes: 0
Views: 651
Reputation: 21
If you are in the debug mode you can use Diagnostic Tools
While your application is started go to the menu:
Debug --> Windows --> Show Diagnostic Tools
Upvotes: 1
Reputation: 9519
If task is not calculted by procesor will time in stopwatch run and waste.
If you look at the source code of the System.Diagnostics.Stopwatch
you will see that it actually doesn't run, there is no waste. It has two timestamps start
and end
and it actually count the elapsed
by calculating and adding the periods between these. Notice that you can start and stop Stopwatch
multiple times, it will measure the cumulative period between these runs. So the answer is yes it will calculate also the time while thread is inactive.
Also by the Microsoft you should be careful when running Stopwatch
on multiprocessor environment:
On a multiprocessor computer, it does not matter which processor the thread runs on. However, because of bugs in the BIOS or the Hardware Abstraction Layer (HAL), you can get different timing results on different processors. To specify processor affinity for a thread, use the
ProcessThread.ProcessorAffinity
method.
On the other hand if you want to measure how much time CPU spent executing the code take a look at the following link: ExecutionStopwatch. It basically leverages the usage of the GetThreadTimes
and measure how much time thread spent running together in kernel or user mode.
Upvotes: 2