C++ Sleep functions for windows & Linux – Code Example

Total
0
Shares

In this article we will look at few methods to implement C++ Sleep functionality. There are various issues in delaying a thread, process or event. First of all none of the methods are accurate at millisecond precision. Second, they are platform specific and their declarations are different according to windows or linux operating systems.

Code Example

1. Sleep in Windows

In Windows, we can use Sleep() function which accepts number of milliseconds to delay the process. It’s syntax is –

void Sleep(
  [in] DWORD dwMilliseconds
);

You can use windows Sleep in c++ code as –

#include <windows.h>
// ...
Sleep(5000); // 5s

2. sleep in Linux

Linux provides sleep function which accepts time in seconds.

#include <unistd.h>
// ...
sleep(5); // 5s

3. nanosleep in Linux

If you want more higher resolution of delay then you can use nanosleep() function. It accepts time in nanoseconds. The acceptable values are from 0 to 999999999.

#include <time.h>
// ...
nonosleep(3747384)

4. usleep in Linux

If your requirements are for microseconds, then you can use usleep in Linux. Use it like this –

#include <unistd.h>
// ...
usleep(5000000) // 5 seconds

5. Using chrono in C++ 11

If you are using c++ 11 then you can use chrono library along with thread library. It is the latest method of delaying a program execution.

a. Using chrono::seconds –

#include <thread>
#include <chrono>
// ...
std::this_thread::sleep_for(std::chrono::seconds(5)); // 5s

b. Using chrono::milliseconds –

#include <thread>
#include <chrono>
// ...
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // 5s

c. Using chrono::microseconds –

#include <thread>
#include <chrono>
// ...
std::this_thread::sleep_for(std::chrono::microseconds(5000*1000)); // 5s

d. Using chrono::nanoseconds –

#include <thread>
#include <chrono>
// ...
std::this_thread::sleep_for(std::chrono::nanoseconds(5000*1000*1000)); // 5s