Tag Archives: Sleep

How to sleep for milliseconds in C++

  1. Use usleep (POSIX)
  2. Use Sleep (Windows)
  3. Use Boost.Thread
  4. Use std::this_thread::sleep_for (C++11)

Method 1: Use usleep (POSIX)

#include <unistd.h>

int main()
{
    usleep(500);
}

Method 2: Use Sleep (Windows)

#include <Windows.h>

int main()
{
    Sleep(500);
}

Method 3: Use Boost.Thread

#include <boost/thread/thread.hpp>
int main()
{
    boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}

Method 4: Use std::this_thread::sleep_for (C++11)

#include <chrono>
#include <thread>

int main()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
}