Various timers in C # Stopwatch, TimeSpan

Source: Internet
Author: User

1. Use Stopwatch class (System.Diagnostics.Stopwatch)

Stopwatch instances can measure the elapsed time of a single time interval, or they can measure the total elapsed time of multiple time intervals. In a typical Stopwatch scenario, call the Start method, then call the Stop method, and finally use the Elapsed property to check the run time.

The Stopwatch instance is either running or stopped, and isrunning can be used to determine the current state of the Stopwatch. Start the measurement run time using start, or stop to measure the elapsed time using stop. Query run time values through properties Elapsed, Elapsedmilliseconds, or elapsedticks. You can query the run time properties when the instance is running or stopped. The run time property is steadily incremented during the Stopwatch run, and remains the same when the instance is stopped.

by default, the run time value of the Stopwatch instance is equal to the sum of all measured intervals. The cumulative run time count is started each time the start is called, and the current interval measurement is ended each time the Stop is called, and the accumulated run time value is frozen. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.

The stopwatch counts the ticks in the base timer mechanism to measure elapsed time. If the installed hardware and operating system support counters for high-resolution performance, the Stopwatch class will use this counter to measure elapsed time, otherwise the Stopwatch class will use system counters to measure elapsed time. Use the Frequency and Ishighresolution fields to determine the accuracy and resolution of the Stopwatch timing implementation.

Example
System.Diagnostics.Stopwatch Stopwatch = new System.Diagnostics.Stopwatch (); Stopwatch. Start ();//Task 1...stopwatch. Stop (); _result. Text + = "<p> Task 1 spents:" + stopwatch. Elapsedticks + ". </p> "; stopwatch. Reset (); Without Reset, the task 1 will be accumulated into task 2stopwatch. Start ();//Task 2...stopwatch. Stop (); _result. Text + = "<p> Task 2 spents:" + stopwatch. Elapsedticks + ". </p> ";



2. Windows-based standard timer (System.Windows.Forms.Timer)

Windows timers are designed for single-threaded environments, and this timer is the simplest one, as long as you drag the Timer control from the Toolbox onto the form, and then set the properties such as event and interval time.

3. Server-Based Timers (System.Timers.Timer)

System.Timers.Timer does not rely on forms, is a wake-up thread from the thread pool, is an updated version of the traditional timer optimized for running on a server environment.

4. Thread Timer (System.Threading.Timer)

The thread timer is also not dependent on the form, and is a simple, lightweight timer that uses callback methods instead of using events and is supported by thread pool threads.

5, System.Environment.TickCount

The TickCount property is used to get the millisecond count from the computer's system timer.

Usage:



6. UseTimeSpan Class (System.TimeSpan)

TimeSpan the object represents the time interval or duration, measured by positive and negative days, hours, minutes, seconds, and the number of seconds. The maximum time unit used to measure durations is days. Larger units of time (such as months and years) differ in number of days, so to maintain consistency, the interval is measured in days.

      TimeSpan The value of the object is equal to the number of ticks that represent the time interval. One tick equals 100 nanoseconds, timespan the value of the object ranges in MinValue and MaxValue

The TimeSpan value can be expressed as [-]D. hh:mm:SS. FF, where the minus sign is optional, it indicates a negative time interval, theD component represents the day, thehh represents the hour (24-hour system), themm represents the minute, theSS represents the seconds, and the FF is the decimal part of the second. That is, the time interval includes the number of positive and negative days, the number of days, the amount of time remaining for less than one day, or the length of less than one day. For example, the text of a TimeSpan object initialized to a 1.0e+13 scale represents "11.13:46:40", which is 11 days, 13 hours, 46 minutes, and 40 seconds.

Usage:

        <summary>        //Description:///        1. Gets the millisecond difference between "current time" and "Compare Time"//        2. Static method/     //Author: Hui Yifang //Create date:2014-03-06//</summary>//        <param name= "Comparetime" > Compare time </param>        //<returns> Millisecond difference </returns> public        static int Getdiffermillisecond (DateTime comparetime)        {            return DateTime.Now.Subtract (comparetime). Milliseconds;        }

 DateTime                            Temptime = DateTime.Now; _logger. Info ("Task Wait Begin", String.)                                                    Format ("{0} starts execution {1} tasks", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"),                            Exectask));                                try {task.waitall (tasks);//wait for the execution of the send task to complete Uptaskstatus (_mddatacubeofjobinfotaskmodel.plancode, _actionset); Determines whether the batch data is completed} catch {} _logger. Info ("Task Wait End", String.) Format ("{0} has completed {1} tasks, time consuming {2}/ms", DateTime.Now.ToString ("Yyyy-mm-dd H H:mm:ss "), Exectask, Timehelper.getdiffermillisecond (Temptime))); 


Various timers in C # Stopwatch, TimeSpan

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.