Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Millisecond sleep on Windows

📅 2015-Oct-26 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ sleep, usleep ⬩ 📚 Archive

I had code that slept for a certain number of milliseconds using the usleep function available from unistd.h on Unix systems. This function sleeps in microseconds.

Code:

#include <unistd.h>

void msleep(int ms)
{
    usleep(ms * 1000);
}

This code cannot be ported to Windows because it does not have usleep. You have two alternatives: use the high performance timer or the ancient Sleep call.

Information on Sleep can be found here. Include the Windows.h to be able to compile it. I changed the code to:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

void msleep(int ms)
{
#ifdef _WIN32
    Sleep(ms);
#else
    usleep(ms * 1000);
#endif
}

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧