简体   繁体   中英

How to measure actual time CPU spent executing the code using the stopwatch?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM