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

Obtaining Microsecond Precision in .NET

, 2 Apr 2013
Rate this:
Please Sign up or sign in to vote.
Obtaining microsecond precision using .NET without Platform Invoke.
This is an old version of the currently published tip/trick.

Introduction

It is has been widely toted that Microsecond Precision (μs) scale time is not possible on .NET or Mono due to many issues which I will not endeavor into explaining.

Based on some of this I originally had setup a task for myself to write a good portable μs scale timer which performed the necessary platform invocation.

After I was done I realized that there is nothing "scientifically" stopping .Net from having this precision based on the fact that the caller executes the invocation and obtains the result and the GC cannot interrupt platform invocation calls so long as you do not pass a manged type.

E.g., if I pass a plain old pointer to a un-managed function there is nothing for the GC to interrupt or stop unless the Kernel itself interrupts the call for something.

I originally though about using unsafe code but then I realized that I was just going closer to using platform invocation.

I thought about trying to obtain precise clock cycles using a static constructor which forced a GC and then ran to determine things like call overhead and whatnot but I felt that there was more time being spent on trying to obtain information then actually sleeping for the user which was the goal.

I then realized something even more bold and interesting... Sockets have a microsecond precision due to signaling and they are usable from the .NET Framework and there is a Poll method which actually accepts the amount of time in Microseconds (μs).

After some quick tests I realized I had something which was a lightweight sealed class with all static members with no more resources than a single socket.

I tricked the socket into always being busy and then I used the Poll method to obtain the desired sleep time in Microsecond Precision(μs).

I want to know what everyone thinks about this and if anyone sees anything glaring out at me which I did not also take into account.

Here is the class code and testing code complete with platform invocation methods (found here on Stack Overflow @ usleep is obsolte...) for comparison and testing.

/// <summary>
/// A Cross platform implementation which can delay time on the microsecond(μs) scale.
/// It operates at a frequencies which are faster then most Platform Invoke
/// results can provide due to the use of Kernel Calls under the hood.
/// Requires Libc.so@usleep on Mono and QueryPerformanceCounter on Windows for uSleep static
/// </summary>
/// <notes>A Tcp Socket will be created on port 7777 by default to help keep track
/// of time. No connections will be recieved from this socket.</notes>
public sealed class μTimer
{
    #region Not Applicable for the MicroFramework
#if(!MF)

    #region Uncesessary Interop (Left for Comparison)
#if MONO
    using System.Runtime.InteropServices;
    [System.Runtime.InteropServices.DllImport("libc.so")] //.a , Not Portable
    static extern int usleep (uint amount);

    ///<notes>The type useconds_t is an unsigned integer type capable of holding integers
    ///in the range [0,1000000]. Programs will be more portable
    ///if they never mention this type explicitly. </notes>
    void uSleep(int waitTime) { usleep(waitTime); }
#else
    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceFrequency(out long lpFrequency);

    /// <summary>
    /// Performs a sleep using a plaform dependent but proven method
    /// </summary>
    /// <param name="amount">The amount of time to sleep in microseconds(μs)</param>
    public static void uSleep(TimeSpan amount) { μTimer.uSleep(((int)(amount.TotalMilliseconds * 1000))); }

    /// <summary>
    /// Performs uSleep by convention of waiting on performance couters
    /// </summary>
    /// <param name="waitTime">The amount of time to wait</param>
    public static void uSleep(int waitTime)
    {
        long time1 = 0, time2 = 0, freq = 0;

        QueryPerformanceCounter(out time1);
        QueryPerformanceFrequency(out freq);

        do
        {
            QueryPerformanceCounter(out time2);
        } while ((time2 - time1) < waitTime);
    }
#endif
    #endregion
#endif
    #endregion

    #region Statics

    //Who but me
    const ushort Port = 7777;

    //Since System.Timespan.TickerPerMicrosecond is constantly 10,000
    public const long TicksPerMicrosecond = 10;

    /// <summary>
    /// A divider used to scale time for waiting
    /// </summary>
    public const long Divider = 1000;

    /// <summary>
    /// The socket we use to keep track of time
    /// </summary>
    static Socket m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    /// <summary>
    /// The memory we give to the socket for events which should not occur
    /// </summary>
    static SocketAsyncEventArgs m_SocketMemory = new SocketAsyncEventArgs();

    /// <summary>
    /// Handles the creation of resources used to provide the μSleep method.
    /// </summary>
    static μTimer()
    {
        try
        {
            //Listen on the Loopback adapter on the specified port
            m_Socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, Port));

            //Only for 1 client
            m_Socket.Listen(1);

            //Assign an event now because in Begin process we will not call it if the even will not raise
            m_SocketMemory.Completed += BeginProcess;

            //If the SocketAsyncEventArgs will not raise it's own event we will call it now
            if (!m_Socket.AcceptAsync(m_SocketMemory))
            {
                BeginProcess(typeof(μTimer), m_SocketMemory);
            }
        }
        catch
        {
            throw;
        }
    }

    /// <summary>
    /// Handles processing on the master time socket.
    /// This should never occcur.
    /// </summary>
    /// <param name="sender">The sender of the event</param>
    /// <param name="e">The SocketAsyncEventArgs from the event</param>
    static void BeginProcess(object sender, SocketAsyncEventArgs e)
    {
        if (e.LastOperation == SocketAsyncOperation.Connect)
        {
            //Dispose the SOB who interrupted us
            Socket dontCare = e.AcceptSocket;
            dontCare.Dispose();

            //Call accept again
            if (!m_Socket.AcceptAsync(e))
            {
                //We are being DOS Attacked..
                throw new System.InvalidProgramException(
                  "A Connection to the system was made by a unauthorized means.");
            }
        }
    }

    /// <summary>
    /// Performs a sleep using a method engineered by Julius Friedman (juliusfriedman@gmail.com)
    /// </summary>
    /// <param name="amount">The amount of time to Sleep</param>
    public static void μSleep(TimeSpan amount)
    {
        //Sample the system clock
        DateTime now = DateTime.UtcNow, then = DateTime.UtcNow;
        TimeSpan waited = now - then;
        //If cpu time is not fast enough to accomadate then you are in bigger trouble then you know
        if (waited > amount) return;
        //A normal sleep with an amount less that 1 but greater than 0 Millisecond will not switch
        else System.Threading.Thread.Sleep(amount - waited);
        waited = now - then;//Waste cycles and calculate time waited in ticks again
        if (waited > amount) return;
        else unchecked
            {
                //Scale time, basis of theory is we shouldn't be able to read from a socket in Accept mode 
                //and it should take more time than a 1000th of the time we need
                if (m_Socket.Poll(((int)((amount.Ticks - waited.Ticks / 
                        TicksPerMicrosecond) / Divider)), SelectMode.SelectRead))
                {
                    //We didn't sleep
                    //Sample the system clock
                    then = DateTime.UtcNow;
                    //Calculate waited
                    //Subtract time already waited from amount
                    amount -= waited;
                    //Waited set to now - then to determine wait
                    waited = now - then;
                    //return or utilize rest of slice sleeping
                    if (waited > amount) return;
                    else System.Threading.Thread.Sleep(amount - waited);
                }
            }
    }

    /// <summary>
    /// Performs a sleep using a method engineered by Julius Friedman (juliusfriedman@gmail.com)
    /// </summary>
    /// <param name="amount">The amount of time to Sleep in microseconds(μs) </param>
    public static void μSleep(int amount) { μTimer.μSleep(TimeSpan.FromMilliseconds(amount * 1000)); }

    #endregion
}

#endregion

Here is the testing code:

static void RunTest(Action test, int count = 0)
{
    System.Console.Clear();
    Console.BackgroundColor = ConsoleColor.Blue;
    Console.WriteLine("About to run test: " + test.Method.Name);
    Console.WriteLine("Press Q to skip or any other key to continue.");
    Console.BackgroundColor = ConsoleColor.Black;
    if (Console.ReadKey().Key == ConsoleKey.Q) return;
    else
    {
        Dictionary<int, Exception> log = null;

        int run = count, failures = 0, successes = 0; bool multipleTests = count > 0;

        if (multipleTests) log = new Dictionary<int, Exception>();

    Test:
        try
        {
            System.Threading.Interlocked.Decrement(ref run);
            test();
            writeSuccess(multipleTests);
            System.Threading.Interlocked.Increment(ref successes);
        }
        catch (Exception ex)
        {
            System.Threading.Interlocked.Increment(ref failures);
            writeNotice(ex);
            if (multipleTests)
            {
                log.Add(run, ex);
                System.Threading.Thread.Yield();
            }
        }

        if (run >= 0) goto Test;
        else if (multipleTests)
        {
            if (failures > successes) writeNotice(new Exception("More Failures then Successes"));
            else writeSuccess(false, failures + " Failures, " + --successes + " Successes");
        }

        ConsoleKey input = Console.ReadKey().Key;

        if (input == ConsoleKey.W) goto Test;
        else if (input == ConsoleKey.D) System.Diagnostics.Debugger.Break();
    }
}

public static void TestTimer()
{

    TimeSpan delay = TimeSpan.FromTicks(TimeSpan.TicksPerMillisecond / 1000);

    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();

    TimeSpan watch = TimeSpan.Zero;

    while ((watch = sw.Elapsed) < delay - TimeSpan.FromTicks(TimeSpan.TicksPerMillisecond)) 
       writeNotice(new Exception("Sleeping"), ConsoleColor.DarkRed, false);
    sw.Stop();

    System.GC.WaitForPendingFinalizers();
    System.GC.WaitForFullGCComplete();

    //Sample system clock
    DateTime now = DateTime.UtcNow;

    //Calculate when it should be when the sleep is done
    DateTime shouldBe = now + delay;

    //Use the performance counter method
    μTimer.uSleep(delay);

    //Sample the clock
    DateTime then = DateTime.UtcNow;

    //Calculate the result
    TimeSpan pActually = then - now;

    //Use Poll Method
    now = DateTime.UtcNow;

    //Calculate when it should be when the sleep is done
    shouldBe = now + delay;

    //Sleep using my method
    μTimer.μSleep(delay);

    //Sample the clock
    then = DateTime.UtcNow;

    //Calculate the result
    TimeSpan μActually = then - now;

    if (μActually > delay)
    {
        throw new Exception("μTimer Precision is not Correct!");
    }
    else if (pActually > delay)
    {
        throw new Exception("Performance Counter Precision is not Correct!");
    }
    else if (watch > delay)
    {
        throw new Exception("StopWatch Counter Precision is not Correct!");
    }
    else if (pActually < μActually)
    {
        throw new Exception("Performance Counter beat Timer!");
    }
    else if (watch < μActually)
    {
        throw new Exception("StopWatch Counter beat Timer!");
    }
    else
    {
        writeNotice(new Exception(("Timer Took: " + μActually + 
          " PerformanceCounter Took: " + pActually)), ConsoleColor.DarkGreen, false);
    }
}

Called like this:

static void Main() { RunTest(TestTimer, 7777); }

Even when using just the Performance counters there are some failures as you might come to expect, however in all cases I find my method is faster then the platform invocation and the counters.

Let me know if I am too high on my horse to see the big picture here or if I actually achieved something which others may find useful!

I updated the test code and it shows how to use a StopWatch to wait also.. it seems that is NOT faster because it uses the performance counters mine already beats...

The reason for this in short, is that my code uses IOCompletionPorts under the hood in Windows and on Unix it is using system calls.

See MSDN, tutorialspoint.

I am also confirming this working in the MicroFx as well as other places you may not expect e.g. Java et al and depends on how the underlying implementation provides the Poll method.

But in all honesty, is there anything really wrong with this?

License

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

About the Author

jfriedman
Software Developer (Senior) ASTI Transportation Inc.
United States United States
Livin in a lonely world, caught the midnight train going anywhere... Only thing is it was a runaway train... and it ain't ever goin back...
 
v//
Follow on   Twitter   Google+

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.
 
GeneralMy vote of 1 PinmemberMember 1025864422-Jun-14 11:49 
GeneralRe: My vote of 1 Pinpremiumjfriedman22-Jun-14 12:48 
GeneralMy vote of 1 Pinpremiumphil.o6-Jun-14 9:20 
GeneralRe: My vote of 1 Pinpremiumjfriedman7-Jun-14 2:48 
GeneralRe: My vote of 1 Pinmember_groo_10-Jun-14 4:57 
GeneralRe: My vote of 1 Pinpremiumjfriedman10-Jun-14 5:06 
Bug[My vote of 1] You are not measuring the elapsed time correctly Pinmember_groo_6-May-14 20:56 
GeneralRe: [My vote of 1] You are not measuring the elapsed time correctly Pinpremiumjfriedman7-May-14 5:08 
GeneralMy vote of 1 PinmemberNchantim8-Jan-14 4:57 
GeneralRe: My vote of 1 Pinprofessionaljfriedman16-Jan-14 18:02 
QuestionTried it, but it doesn't seem accurate [modified] Pinmember_groo_16-Nov-13 2:18 
AnswerRe: Tried it, but it doesn't seem accurate Pinprofessionaljfriedman16-Jan-14 18:15 
GeneralRe: Tried it, but it doesn't seem accurate Pinmember_groo_18-Apr-14 14:28 
GeneralRe: Tried it, but it doesn't seem accurate Pinpremiumjfriedman30-Apr-14 14:30 
GeneralRe: Tried it, but it doesn't seem accurate Pinmember_groo_6-May-14 1:51 
GeneralRe: Tried it, but it doesn't seem accurate Pinpremiumjfriedman6-May-14 1:58 
GeneralRe: Tried it, but it doesn't seem accurate Pinmember_groo_6-May-14 5:35 
GeneralRe: Tried it, but it doesn't seem accurate Pinpremiumjfriedman6-May-14 5:53 
QuestionHow to calculate the sleep time? PinmemberBlackDogSpark12-Jun-13 13:41 
AnswerRe: How to calculate the sleep time? Pinprofessionaljfriedman5-Jul-13 6:43 
QuestionI'm confused. How to use this to replace System.Timers.Timer loop? PinmemberBlackDogSpark10-Jun-13 8:13 
AnswerRe: I'm confused. How to use this to replace System.Timers.Timer loop? Pinprofessionaljfriedman10-Jun-13 9:33 
GeneralRe: I'm confused. How to use this to replace System.Timers.Timer loop? PinmemberBlackDogSpark10-Jun-13 10:04 
GeneralRe: I'm confused. How to use this to replace System.Timers.Timer loop? Pinprofessionaljfriedman5-Jul-13 6:45 
QuestionWhere to find Socket.WaitRead()? PinmemberNils-Erik Thorén22-Apr-13 3:00 

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 | Mobile
Web04 | 2.8.140721.1 | Last Updated 2 Apr 2013
Article Copyright 2013 by jfriedman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid