Skip to content

Instantly share code, notes, and snippets.

@Youka
Created November 22, 2014 13:44
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Youka/4153f12cf2e17a77314c to your computer and use it in GitHub Desktop.
Save Youka/4153f12cf2e17a77314c to your computer and use it in GitHub Desktop.
Windows nanosleep
#include <windows.h> /* WinAPI */
/* Windows sleep in 100ns units */
BOOLEAN nanosleep(LONGLONG ns){
/* Declarations */
HANDLE timer; /* Timer handle */
LARGE_INTEGER li; /* Time defintion */
/* Create timer */
if(!(timer = CreateWaitableTimer(NULL, TRUE, NULL)))
return FALSE;
/* Set timer properties */
li.QuadPart = -ns;
if(!SetWaitableTimer(timer, &li, 0, NULL, NULL, FALSE)){
CloseHandle(timer);
return FALSE;
}
/* Start & wait for timer */
WaitForSingleObject(timer, INFINITE);
/* Clean resources */
CloseHandle(timer);
/* Slept without problems */
return TRUE;
}
@phuicy
Copy link

phuicy commented Nov 5, 2015

Awesome

@Janonard
Copy link

Thanks alot!

@gbburkhardt
Copy link

I don't think this is quite correct. The value passed to SetWaitableTimer should have units of 100ns. See Using Waitable Timer Objects.

@gbburkhardt
Copy link

For Windows versions 2004 and after, use CREATE_WAITABLE_TIMER_HIGH_RESOLUTION. See Windows Timer Resolution: The Great Rule Change

@Youka
Copy link
Author

Youka commented Nov 13, 2023

@gbburkhardt Thanks for the update! "The Great Rule Change" was easy to miss.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment