High resolution timer [duplicate]

In regards to the information that the OP was specifically asking about the Timer class which fires events at regular intervals. I have amended this answer, with my old answer below the horizontal rule.

I tested the following code with the Timer class, and it seems like it can get at least within the 14 – 15 millisecond range on my machine. Try it out for yourself and see if you can reproduce this. So sub-50 millisecond response times are possible, but it can’t get down to exactly one millisecond.

using System;
using System.Timers;
using System.Diagnostics;

public static class Test
{
    public static void Main(String[] args)
    {
        Timer timer = new Timer();
        timer.Interval = 1;
        timer.Enabled = true;

        Stopwatch sw = Stopwatch.StartNew();
        long start = 0;
        long end = sw.ElapsedMilliseconds;

        timer.Elapsed += (o, e) =>
        {
            start = end;
            end = sw.ElapsedMilliseconds;
            Console.WriteLine("{0} milliseconds passed", end - start);
        };

        Console.ReadLine();
    }
}

NB: The following is my old answer, when I thought the OP was talking about timing things. The following is merely useful information with respect to timing the duration of things, but doesn’t provide any way of firing events at a regular interval. For that purpose, the Timer class is necessary.

Try using the Stopwatch class within System.Diagnostics: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

You can query it to check if it’s high resolution through it’s IsHighResolution field. Also, you can check the exact resolution of the Stopwatch:

int resolution = 1E9 / Stopwatch.Frequency;
Console.WriteLine("The minimum measurable time on this system is: {0} nanoseconds", resolution);

If you’re worried about where this is actually sourced, the documentation seems to imply that it actually internally calls the lower level Win32 functions:

The Stopwatch class assists the manipulation of timing-related
performance counters within managed code. Specifically, the Frequency
field and GetTimestamp method can be used in place of the unmanaged
Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

Leave a Comment