Microsecond and Millisecond C # timer[Goto]

Source: Internet
Author: User
Tags microsecond timer dell inspiron 1545 intel core 2 duo

Article go to: Http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer

Introduction
Anyone who have used the. NET System.Timers.Timer class for low interval times would realise that it does don't offer a very h IgH resolution. The resolution would be system dependant, but a maximum resolution was usually around 15ms (System.Windows.Forms.Timer has a n Even worse resolution, although it is unlikely a UI would need to being updated this fast). Significantly better performance can be achieved using the WIN32 multimedia timer (there is various. NET projects that WR AP this timer); However, there is no timers available in the Microsecond range.

The problem I encountered is that I needed to send a Ethernet UDP message packet out every 800µs (0.8ms); It did not matter if a packet is slightly delayed or did not go off exactly 800µs after the last one. Basically, what I needed is a microsecond timer that is accurate the majority of the time.

The fundamental problem with a software timer in the region of 1ms are that Windows is a non real-time Operating System (RT OS) and is not suitable for generating regular and accurate events around the 1ms mark. MicroTimer cannot and does not solve this problem; However, it does offer a microsecond timer which offers a reasonable degree of accuracy (approx. 1µs) the majority (approx . 99.9%) of the time. The trouble is, the 0.1% of the time, the timer can be very inaccurate (whilst the Operating System gives some of the proc Essing time to other threads and processes). The accuracy is highly system/processor dependant; A faster system would result in a more accurate timer.

The beauty of MicroTimer is that it's called in a very similar the "to" existing "class; However, the interval is a set in microseconds (as opposed to milliseconds in System.Timers.Timer). On each timed event, MicroTimer invokes the predefined (Ontimedevent) callback function. The Microtimereventargs properties provide information (to the microsecond) on when exactly (and how late) the timer was I Nvoked.
Using the Code

' MicroLibrary.cs ' encompasses three classes (under the namespace Microlibrary):

Microstopwatch-this derives from and extends the System.Diagnostics.Stopwatch class; Importantly, it provides the additional property elapsedmicroseconds. This is useful as a standalone class where the elapsed microseconds from when the stopwatch were started can be directly OB tained.
Microtimer-designed so it operates in a very similar the-the-System.Timers.Timer class, it has a Timer interval in mi Croseconds and Start/stop methods (or Enabled property). The timer implements a custom event handler (Microtimerelapsedeventhandler) that fires every interval. The Notificationtimer function is where the ' work ' was done and was run in a separate high priority thread. It should be noted this MicroTimer is inefficient and very processor hungry as the Notificationtimer function runs a tight While loop until the elapsed microseconds is greater than the next interval. The while loop uses a SpinWait that is not a sleep but runs for a few nanoseconds and effectively puts the thread to Slee P without relinquishing the remainder of its CPU time slot. This is not ideal; However, for such small intervals, this is probably the only practical solution.
Microtimereventargs-derived from System.EventArgs, this class provides a object for holding information about the event . Namely, the number of times the event has fired, the absolute time (in microseconds) from when the timer is started, how Late the event is and the execution time of the callback function (for the previous event). From this data, a range of timer information can derived.

By design, the amount of work-done in the callback function (Ontimedevent) must is small (e.g. update a variable or fire O FF a UDP packet). To this end, the work of the callback function must take significantly less time than the timer interval. Separate threads could is spawned for longer tasks; However, this goes outside the scope of this article. As discussed earlier, because Windows is isn't a real time Operating System, the callback function (ontimedevent) may be lat E If this happens and any particular interval is delayed, the There is the options:

Either:set the property Ignoreeventiflateby whereby the callback function (Ontimedevent) won't be called if the timer Is late by the specified number of microseconds. The advantage of this is the timer won't attempt to ' catch up ', i.e., it won't call the callback function in quick s Uccession in a attempt to catch up. The disadvantage is that some events would be missed.
Or:by default, MicroTimer'll always try and catch up on the next interval. The advantage of the number of the times the ontimeevent is called would always be correct for the total elapsed time ( Which is, the ontimedevent must take significantly less time than the interval; If it takes a similar or longer time, MicroTimer can never ' catch up ' and the timer event would always be late). The disadvantage of this was when it's trying to ' catch up ', the actual interval achieved would be much less than the Requir Ed interval as the callback function is called in quick succession in a attempt to catch up.

The timer is stopped in one of three ways:

Stop (or Enabled = False)-This method stops the timer is setting a flag to instruct the timer to stop, however, this CAL L executes asynchronously i.e. the call to Stop would return immediately (but the current timer event could not be finished ).
Stopandwait-this method stops the timer synchronously, it won't return until the current timer (callback) event have F Inished and the timer thread has terminated. Stopandwait also have an overload method that accepts a timeout (in MS), if the timer successfully stops within the timeout Period then true was returned, else false is returned.
Abort-this method May is used as a last resort to terminate the timer thread, for example, to abort the timer if it had Not stopped after waiting 1sec (1000ms) use:
if (!microtimer.stopandwait ()) {Microtimer.abort ();}

The code below shows the Microlibrary namespace (MicroLibrary.cs) which contains the three classes, Microstopwatch, Microt Imer and Microtimereventargs. See the ' Download source ' link above.

The code below shows a very simple (console application) Implementation of the MicroTimer class with the interval set to 1 , 000µs (1ms). See the ' Download Console Demo project ' link above.

The screenshot below shows the console output. The performance varies on different runs, but is usually accurate to 1µs. Due to system caching, the accuracy is worse o n the first run and got better after the first few events. This test is on a 2GHz Dell Inspiron 1545 with an Intel Core 2 Duo (running Windows 7 64bit). The performance improved significantly on faster machines.

It is very unlikely a UI would need to being updated at intervals in the millisecond range. Purely for the point of demonstration, the ' Download WinForms Demo project ' link above contains a very simple WinForms app Lication that updates a UI using the MicroTimer. The screenshot below demonstrates the application acting as a stopwatch (with a microsecond display) where the UI is being Updated with the elapsedmicroseconds every 1111µs (1.111ms).

Summary

MicroTimer is designed for situations were a very quick timer is required (around the 1ms mark); However, due to the non real-time nature of the Windows Operating System, it can never is accurate. However, as no other microsecond software timers is available, it does offer a reasonable solution for the This task (and Alt Hough processor hungry, is reasonably accurate on fast systems).

Microsecond and Millisecond C # timer[Goto]

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.