Skip to content

Instantly share code, notes, and snippets.

@GoaLitiuM
Created February 25, 2016 20:50
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 GoaLitiuM/5413bfa971d1910ed753 to your computer and use it in GitHub Desktop.
Save GoaLitiuM/5413bfa971d1910ed753 to your computer and use it in GitHub Desktop.
Usleep() for Windows (C#) + set timer resolution to lowest possible supported by system
using System;
using System.Runtime.InteropServices;
public static class Utility
{
static int ntCurrentResolution = 0;
public static void Usleep(ulong time)
{
if (ntCurrentResolution == 0)
NtSetTimerResolution(1, true, out ntCurrentResolution);
IntPtr timer = CreateWaitableTimer(IntPtr.Zero, true, null);
// negative values are for relative time
long period = -(10 * (long)time);
SetWaitableTimer(timer, ref period, 0, IntPtr.Zero, IntPtr.Zero, false);
WaitForSingleObject(timer, 0xFFFFFFFF);
CloseHandle(timer);
}
[DllImport("ntdll.dll")]
static extern int NtSetTimerResolution(int DesiredResolution, bool SetResolution, out int CurrentResolution);
[DllImport("kernel32.dll")]
static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll")]
static extern bool SetWaitableTimer(IntPtr hTimer, ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern Int32 WaitForSingleObject(IntPtr Handle, uint Wait);
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
}
using System;
using System.Diagnostics;
public static class Program
{
[STAThread]
static void Main()
{
Stopwatch sw = Stopwatch.StartNew();
int times = 1000;
// Utility.Usleep(1) sleeps at lowest possible amount of time
for (int i = 0; i < times; i++)
Utility.Usleep(1);
sw.Stop();
Console.WriteLine((sw.Elapsed.TotalMilliseconds/times).ToString("0.00"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment