Skip to content

Instantly share code, notes, and snippets.

@miho
Created January 11, 2021 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miho/9a32da536fc9644943a2485ade1e8c1a to your computer and use it in GitHub Desktop.
Save miho/9a32da536fc9644943a2485ade1e8c1a to your computer and use it in GitHub Desktop.
using System.Runtime.InteropServices;
using System.Security;
namespace com.bfx.timerutil {
/// <summary> Tools to enable high-resolution timer (1ms). Default timer resolution is 16ms.</summary>
/// Note, that only the resolution of Thread.Sleep() is increased. Task.Delay() is not affected by this
/// increased resolution since the responsible timer is running at fixed 16m rate.
public static class TimerUtil {
private static bool enabled;
/// <summary> Enables high-resolution timer (1ms)</summary>
public static void EnableHighresTimer() {
if(!enabled) {
TimeBeginPeriod(1/*ms*/);
enabled = true;
}
}
/// <summary> Disables high-resolution timer (1ms)</summary>
public static void DisableHighresTimer() {
if(enabled) {
TimeEndPeriod(1/*ms*/);
enabled = false;
}
}
#region native-api
/// <summary> native TimeBeginPeriod() from Windows API.</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)]
private static extern uint TimeBeginPeriod(uint uMilliseconds);
/// <summary> native TimeEndPeriod() from Windows API.</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)]
private static extern uint TimeEndPeriod(uint uMilliseconds);
}
#endregion native-api
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment