how to set timer resolution from C# to 1 ms?

Oleg Vazhnev picture Oleg Vazhnev · Feb 25, 2013 · Viewed 13k times · Source

I've used this tool and noticed that my Windows Server 2008 R2 Standard has a 15 ms resolution while Windows 8 has a 1 ms resolution timer.

I would prefer to set the Timer Resolution to 1 ms on Windows Server 2008 R2 because I'm running low-latency software on it.

I've found this msdn article, but it doesn't explain how to change the Timer resolution from a C# program. How do I do that?

Answer

Matthew Watson picture Matthew Watson · Feb 25, 2013

You can try this:

public static class WinApi
{
    /// <summary>TimeBeginPeriod(). See the Windows API documentation for details.</summary>

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1401:PInvokesShouldNotBeVisible"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("winmm.dll", EntryPoint="timeBeginPeriod", SetLastError=true)]

    public static extern uint TimeBeginPeriod(uint uMilliseconds);

    /// <summary>TimeEndPeriod(). See the Windows API documentation for details.</summary>

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1401:PInvokesShouldNotBeVisible"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("winmm.dll", EntryPoint="timeEndPeriod", SetLastError=true)]

    public static extern uint TimeEndPeriod(uint uMilliseconds);
}

And use it like this:

WinApi.TimeBeginPeriod(1);

And to go back to how it was:

WinApi.TimeEndPeriod(1);