简体   繁体   中英

How can i measure time of some part of code considering sleep time?

I try this:

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

for (i = 0; i < 100; i++) {
    //do here some stuff
    Thread.Sleep(500);
}

timer.Stop();
TimeSpan ts = timer.Elapsed;
Console.WriteLine(ts.Milliseconds);

And it show me 49 milliseconds, but in fact it was performed in like 2 minutes. It's educational tusk and i have to consider sleep time. How can i do this?

The Timespan.Milliseconds property returns the millisecond part of the timespan, after subtracting elapsed seconds, minutes, hours, etc. You probably want TimeSpan.TotalMilliseconds .

See this post for the explanation: C# Timespan Milliseconds vs TotalMilliseconds

I think it is a unit problem, try getting ms directly from stopwatch, this worked for me:

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

    for (int i = 0; i < 20; i++)
    {
        //do here some stuff
        Thread.Sleep(500);
    }

    timer.Stop();
    long ms =  timer.ElapsedMilliseconds;
    Console.WriteLine(ms);
    Console.ReadLine();

Use of Stopwatch will not be accurate, if you want a precise measurement of the execution of some code you will have to use the performance counters that's built into the operating system. Check this out.

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