I have an application that uses Task
(TPL) objects for asynchronous execution.
The main thread waits for a trigger (some TCP packet) and then executes several tasks. What I want to do is to measure the time spent in the tasks.
Take a look at the code. I have some lengthy operation (Generator
), enclosed in Stopwatch's
start/stop.
Task.Factory.StartNew((t) => {
Stopwatch sw = new Stopwatch();
sw.Start();
Generator g = new Generator();
g.GenerateIntervals(); // lengthy operation
sw.Stop();
GlobalStopwatch.Add(sw.Elapsed);
});
Here is the problem. Stopwatch uses DateTime.UtcNow.Ticks
at the moment of Start()
and then again at the moment of Stop()
. Then it subtracts those two to get the elapsed time.
The thing is, some other thread (in a single-threaded system) can get some processor time while the Generator
(from the code) is doing its GenerateIntervals()
lengthy operation. That means that the elapsed time recorded by the stopwatch would contain not only the Generaor.GenerateIntervals()
time, but also the time that the other threads did their job inbetween.
Is there any simple way to know exactly how much of processor time did some method take, not including execution time from other threads as a result of timesharing mechanisms?
The answer to your question is "No"... No, you cannot measure the accumulated time ON THE CPU for a particular thread
.
(Side-rant: I really wish people would read the question and understand it before answering!!!)
Ok, back to your question... the most accurate thing you could do would be to spin off a separate process
for each of your tasks, and then measure the CPU time for the process (which can be done in .Net)... but that's overkill.
If you need help on how to do that, you should ask another question specifically for that.