Elapsed time timings in. Net

Source: Internet
Author: User

In a project, it is often necessary to log records of execution performance (time spent) of some methods, which are implemented in two ways.

StopWatch

Using the Stopwatch class to measure time is very simple. Like the stopwatch in real life, this class of objects can start, stop, zero (reset) operations on the counter, but it is much more accurate than the average stopwatch, which can be accurate to microseconds (that is, one out of 10,000 seconds).

(The following example is from http://www.cnblogs.com/greatandforever/archive/2008/07/23/1249185.html)

To demonstrate the use of stopwatch or a piece of code it. Here is a console application that accumulates all integers from 1 to 1 million:

using System; namespace stopwatchclass{    class  program    {        staticvoid Main (  String[] args)        {            long0;              for (int110000000; i++)            {                + = I;}}}    }
Add Stopwatch Object

The stopwatch class is located in the System.Diagnostics namespace. Here is the code after adding the object:

usingSystem;usingSystem.Diagnostics;namespacestopwatchclass{classProgram {Static voidMain (string[] args) {Stopwatch Timer=NewStopwatch (); LongTotal =0;  for(inti =1; I <=10000000; i++) { Total+=i; }        }    }}
Controlling Stopwatch objects

Stopwatch provides several methods to control the Stopwatch object. The Start method starts a timing operation, and the Stop method stops timing. At this point, if the Start method is used for the second time, the timing will continue and the final timing result is two times the sum of the timings. To avoid this, use the Reset method to zero the object before the second time. None of the three methods require parameters. The code is:

usingSystem;usingSystem.Diagnostics;namespacestopwatchclass{classProgram {Static voidMain (string[] args) {Stopwatch Timer=NewStopwatch (); LongTotal =0; Timer.            Start ();  for(inti =1; I <=10000000; i++) { Total+=i; } timer.        Stop (); }    }}
Read Stopwatch results

The next step is to read the timing results after the timer is over. The Stopwatch class provides the following properties:

    • Elapsed: Returns a TimeSpan object that represents the time interval of the timer;
    • Elapsedmilliseconds: Returns the number of microseconds elapsed, the accuracy is slightly poor, suitable for a slightly longer timing;
    • Elapsedticks: Returns the number of timer ticks (timer ticks) elapsed. The timer scale is the smallest unit of measurement possible for a stopwatch object. The length of the timer tick time is determined by the specific computer and operating system. The value of the frequency static field of the Stopwatch object represents the number of timer ticks that are contained in one second. Notice how it differs from the time unit used by the Ticks property of the timespan.

One of these properties should be selected based on the timing task. In our sample program, the elapsed property provides the required precision, which is used to output the number of microseconds that have elapsed. This is also the highest accuracy of the timespan.
The following is the final program code:

usingSystem;usingSystem.Diagnostics;namespacestopwatchclass{classProgram {Static voidMain (string[] args) {Stopwatch Timer=NewStopwatch (); LongTotal =0; Timer.            Start ();  for(inti =1; I <=10000000; i++) { Total+=i; } timer.            Stop (); decimalMicro = timer. Elapsed.ticks/10m; Console.WriteLine ("execution time was {0:f1} microseconds.", micro); }    }}

In addition, you can use the IsRunning property to see if a stopwatch instance is timing, and use the StartNew method to start a new timer.

DateTime.Now.Ticks

Use DateTime.Now.Ticks to get the number of nanoseconds in the current moment. Using variable 1 to store the current nanosecond before executing the method, and then storing the current nanosecond with variable 2 after executing the method, the corresponding time difference, converted to seconds, is:

Time interval (seconds) = (variable 2-variable 1) * 10000000d

Elapsed time timings in. Net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.