Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

performance - Difference between ElapsedTicks, ElapsedMilliseconds, Elapsed.Milliseconds and Elapsed.TotalMilliseconds? (C#)

I'm totally confused between these 4. What is the difference between ElapsedMilliseconds (long), ElapsedTicks (long), Elapsed.TotalMilliseconds (double) and Elapsed.Milliseconds (int)?

I have a function

    {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        MyTimeConsumingAction();
        sw.Stop();

        sw.//what?
    }

How do I get the correct time consumed by my long running process from elapsed property of Stopwatch object in milliseconds?

Edit: I tried msdn documentation but it isn't anything detailed there..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Elapsed.TotalMilliseconds (double) returns the total number of whole and fractional milliseconds elapsed since inception

e.g. a stopwatch stopped at 1.23456 seconds would return 1234.56 in this property. See TimeSpan.TotalMilliseconds on MSDN

Elapsed.Milliseconds (int) returns the number of whole milliseconds in the current second

e.g. a stopwatch at 1.234 seconds would return 234 in this property. See TimeSpan.Milliseconds

ElapsedTicks (long) returns the ticks since start of the stopwatch.

In the context of the original question, pertaining to the Stopwatch class, ElapsedTicks is the number of ticks elapsed. Ticks occur at the rate of Stopwatch.Frequency, so, to compute seconds elapsed, calculate: numSeconds = stopwatch.ElapsedTicks / Stopwatch.Frequency.

The old answer defined ticks as the number of 100 nanosecond periods, which is correct in the context of the DateTime class, but not correct in the context of the Stopwatch class. See Stopwatch.ElapsedTicks on MSDN.

ElapsedMilliseconds returns a rounded number to the nearest full millisecond, so this might lack precision Elapsed.TotalMilliseconds property can give.

Elapsed.TotalMilliseconds is a double that can return execution times to the partial millisecond while ElapsedMilliseconds is Int64. e.g. a stopwatch at 0.0007 milliseconds would return 0, or 1234.56 milliseconds would return 1234 in this property. So for precision always use Elapsed.TotalMilliseconds.

See Stopwatch.ElapsedMilliseconds on MSDN for clarification.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...