Click here to Skip to main content
Click here to Skip to main content

Microsecond and Millisecond .NET Timer

, 14 Sep 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
MicroTimer: A microsecond and millisecond timer in C# that is used in a similar way to the .NET System.Timers.Timer.
This is an old version of the currently published article.


Anyone who has used the .NET System.Timers.Timer class for low interval times will realise that it does not offer a very high resolution. The resolution will be system dependant, but a maximum resolution is usually around 15ms (System.Windows.Forms.Timer has an even worse resolution, although it is unlikely a UI will need to be updated this fast). Significantly better performance can be achieved using the Win32 multimedia timer (there are various .NET projects that wrap this timer); however, there are no timers available in the microsecond range.

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

The fundamental problem with a software timer in the region of 1ms is that Windows is a non real-time Operating System (RTOS), 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 processing time to other threads and processes). The accuracy is highly system/processor dependant; a faster system will result in a more accurate timer.

The beauty of MicroTimer is that it is called in a very similar way to the existing System.Timers.Timer class; however, the interval is 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 invoked.

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 was started can be directly obtained.
  • MicroTimer - Designed so it operates in a very similar way to the System.Timers.Timer class, it has a timer interval in microseconds, and a Start and Stop method (or Enabled property). It implements a custom event handler (MicroTimerElapsedEventHandler) that fires every interval. The 'NotificationTimer' function is where the 'work' is done, and is run in a separate high priority thread. It should be noted that 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. This is not ideal; however, for such small intervals, this is probably the only practical solution.
  • MicroTimerEventArgs - Derived from System.EventArgs, this class provides an 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 was started, how late the event was, and also the execution time of the callback function (for the previous event). From this data, a range of timer information can be derived.

By design, the amount of work done in the callback function (OnTimedEvent) must be small (e.g., update a variable or fire off a UDP packet). To that end, the work done in the callback function must take significantly less time than the timer interval. Separate threads could be spawned for longer tasks; however, this goes outside the scope of this article. As discussed earlier, because Windows is not a real time Operating System, the callback function (OnTimedEvent) may be late; if this happens and any particular interval is delayed, there are two options:

  • Either: Set the property 'IgnoreEventIfLateBy' whereby the callback function (OnTimedEvent) will not be called if the timer is late by the specified number of microseconds. The advantage of this is the timer will not attempt to 'catch up', i.e., it will not call the callback function in quick succession in an attempt to catch up. The disadvantage is that some events will be missed.
  • Or: By default, MicroTimer will always try and catch up on the next interval. The advantage of this is the number of times the OnTimeEvent is called will always be correct for the total elapsed time (which is why 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 will always be late). The disadvantage of this is when it's trying to 'catch up', the actual interval achieved will be much less than the required interval as the callback function is called in quick succession in an attempt to catch up.

The code below shows the 'MicroLibrary' namespace (MicroLibrary.cs) which contains the three classes, MicroStopwatch, MicroTimer, and MicroTimerEventArgs. See the 'Download source' link above.

using System;
namespace MicroLibrary
    public class MicroStopwatch : System.Diagnostics.Stopwatch
        double m_dMicroSecPerTick = 1000000D / Frequency;
        public MicroStopwatch()
            if (!System.Diagnostics.Stopwatch.IsHighResolution)
                throw new Exception("On this system the high-resolution " + 
                                    "performance counter is not available");
        public long ElapsedMicroseconds
            get{ return (long)(ElapsedTicks * m_dMicroSecPerTick); }
    public class MicroTimer
        public delegate void MicroTimerElapsedEventHandler(object sender, 
                             MicroTimerEventArgs timerEventArgs);
        public event MicroTimerElapsedEventHandler MicroTimerElapsed;
        System.Threading.Thread m_threadTimer = null;
        long m_lIgnoreEventIfLateBy = long.MaxValue;
        long m_lTimerIntervalInMicroSec = 0;
        bool m_bStopTimer = true;
        public MicroTimer()
        public MicroTimer(long lTimerIntervalInMicroseconds)
            Interval = lTimerIntervalInMicroseconds;
        public long Interval
            get { return m_lTimerIntervalInMicroSec; }
            set { m_lTimerIntervalInMicroSec = value; }
        public long IgnoreEventIfLateBy
                return m_lIgnoreEventIfLateBy;
                if (value == 0)
                    m_lIgnoreEventIfLateBy = long.MaxValue;
                    m_lIgnoreEventIfLateBy = value;
        public bool Enabled
                if (value)
                return (m_threadTimer != null && m_threadTimer.IsAlive);
        public void Start()
            if ((m_threadTimer == null || !m_threadTimer.IsAlive) && Interval > 0 )
                m_bStopTimer = false;
                System.Threading.ThreadStart threadStart = 
                  delegate(){ NotificationTimer(Interval, 
                  IgnoreEventIfLateBy, ref m_bStopTimer); };
                m_threadTimer = new System.Threading.Thread(threadStart);
                m_threadTimer.Priority = System.Threading.ThreadPriority.Highest;
        public void Stop()
            m_bStopTimer = true;
            while (Enabled)
        void NotificationTimer(long lTimerInterval, 
             long lIgnoreEventIfLateBy, ref bool bStopTimer)
            int nTimerCount = 0;
            long lNextNotification = 0;
            long lCallbackFunctionExecutionTime = 0;
            MicroStopwatch microStopwatch = new MicroStopwatch();
            while (!bStopTimer)
                lCallbackFunctionExecutionTime = 
                  microStopwatch.ElapsedMicroseconds - lNextNotification;
                lNextNotification += lTimerInterval;
                long lElapsedMicroseconds = 0;
                while ((lElapsedMicroseconds = 
                        microStopwatch.ElapsedMicroseconds) < lNextNotification)
                long lTimerLateBy = lElapsedMicroseconds - (nTimerCount * lTimerInterval);
                if (lTimerLateBy < lIgnoreEventIfLateBy)
                    MicroTimerEventArgs microTimerEventArgs = 
                      new MicroTimerEventArgs(nTimerCount, lElapsedMicroseconds,
                      lTimerLateBy, lCallbackFunctionExecutionTime);
                    MicroTimerElapsed(this, microTimerEventArgs);
    public class MicroTimerEventArgs : EventArgs
        // Simple counter, number times timed event (callback function) executed
        public int TimerCount { get; private set; }
        // Time when timed event was called since timer started
        public long ElapsedMicroseconds { get; private set; }
        // How late the timer was compared to when it should have been called
        public long TimerLateBy { get; private set; }
        // The time it took to execute the previous
        // call to the callback function (OnTimedEvent)
        public long CallbackFunctionExecutionTime { get; private set; }
        public MicroTimerEventArgs(int nTimerCount, long lElapsedMicroseconds, 
               long lTimerLateBy, long lCallbackFunctionExecutionTime)
            TimerCount = nTimerCount;
            ElapsedMicroseconds = lElapsedMicroseconds;
            TimerLateBy = lTimerLateBy;
            CallbackFunctionExecutionTime = lCallbackFunctionExecutionTime;

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 demo project' link above.

using System;
namespace MicroTimerConsoleDemo
    class Program
        static void Main(string[] args)
            Program program = new Program();
        private void MicroTimerTest()
            MicroLibrary.MicroTimer microTimer = new MicroLibrary.MicroTimer();
            microTimer.MicroTimerElapsed += 
              new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent);
            // Call micro timer every 1000µs (1ms)
            microTimer.Interval = 1000;
            // Can choose to ignore event if late by Xµs
            // (by default it will try to catch up)
            // microTimer.IgnoreEventIfLateBy = 500;
            microTimer.Enabled = true;               // Start timer
            // Do something whilst events happening, for demo sleep 2000ms (2sec)
            microTimer.Enabled = false;              // Stop timer
        private void OnTimedEvent(object sender, 
                MicroLibrary.MicroTimerEventArgs timerEventArgs)
            // Do something small that takes significantly less time than Interval
            Console.WriteLine(string.Format("Count = {0:#,0}  Timer = {1:#,0} µs," + 
                " LateBy = {2:#,0} µs, ExecutionTime = {3:#,0} µs",
                timerEventArgs.TimerCount, timerEventArgs.ElapsedMicroseconds, 
                timerEventArgs.TimerLateBy, timerEventArgs.CallbackFunctionExecutionTime));

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



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 be accurate. However, as no other microsecond software timers are available, it does offer a reasonable solution for this task (and although processor hungry, is reasonably accurate on fast systems).


  • 31 July 2010 - Article submitted.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author


United Kingdom United Kingdom
No Biography provided

Comments and Discussions

Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
QuestionSubtle issue regarding Enabled Pinmemberjohn_g_mccabe7hrs 46mins ago 
GeneralMy vote of 5 PinmemberBob Bryan20-Feb-15 22:09 
GeneralRe: My vote of 5 Pinmemberken.loveday21-Feb-15 23:17 
QuestionC++ alternative to MicroTimer? PinmemberMember 1140647327-Jan-15 9:18 
AnswerRe: C++ alternative to MicroTimer? Pinmemberken.loveday27-Jan-15 10:37 
AnswerRe: C++ alternative to MicroTimer? PinmemberBob Bryan20-Feb-15 20:51 
Question1 second = 985 milliseconds? [modified] PinmemberAendie Bauer19-Jan-15 11:36 
AnswerRe: 1 second = 985 milliseconds? PinprotectorPIEBALDconsult19-Jan-15 12:20 
GeneralNASA should avoid these timers... PinmemberAendie Bauer20-Jan-15 4:33 
GeneralRe: NASA should avoid these timers... Pinmemberken.loveday20-Jan-15 11:45 
GeneralRe: 1 second = 985 milliseconds? Pinmemberken.loveday20-Jan-15 11:43 
QuestionAny MicroTimer Overhead Profiling? PinmemberMohamed Elkammar30-May-14 16:25 
AnswerRe: Any MicroTimer Overhead Profiling? Pinmemberken.loveday2-Jun-14 12:16 
GeneralMy vote of 5 Pinmembergaksoftware26-May-14 6:12 
BugNull check for event subscription. [modified] PinmemberNelval11-Mar-14 1:01 
GeneralRe: Null check for event subscription. Pinmemberken.loveday11-Mar-14 11:10 
GeneralJust a tip PinmemberMember 1057741712-Feb-14 16:46 
GeneralRe: Just a tip Pinmemberken.loveday13-Feb-14 11:15 
QuestionCPU load causes timer to be late PinmemberStephan Stricker7-Feb-14 9:37 
AnswerRe: CPU load causes timer to be late Pinmemberken.loveday7-Feb-14 12:39 
QuestionI have Compile Errors PinmemberMember 1052279614-Jan-14 1:06 
AnswerRe: I have Compile Errors Pinmemberken.loveday14-Jan-14 11:46 
GeneralRe: I have Compile Errors PinmemberMember 1052279614-Jan-14 16:05 
GeneralRe: I have Compile Errors Pinmemberken.loveday15-Jan-14 9:38 
QuestionPause PinmembersamerMarounAzar9-Nov-13 0:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150302.1 | Last Updated 14 Sep 2010
Article Copyright 2010 by ken.loveday
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid