Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross platform Sleep function for C++

Is it possible with macros make cross platform Sleep code? For example

#ifdef LINUX #include <header_for_linux_sleep_function.h> #endif #ifdef WINDOWS #include <header_for_windows_sleep_function.h> #endif ... Sleep(miliseconds); ... 
like image 623
ElSajko Avatar asked Jun 06 '12 16:06

ElSajko


People also ask

Does C have a sleep function?

The sleep() method in the C programming language allows you to wait for just a current thread for a set amount of time. The sleep() function will sleep the present executable for the time specified by the thread.

What does sleep () do in C ++?

The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process.

Which C library has sleep?

sleep() function is provided by unistd. h library which is a short cut of Unix standard library.

Where is the sleep function in C?

sleep(3) is in unistd. h , not stdlib. h .


1 Answers

Yup. But this only works in C++11 and later.

#include <chrono> #include <thread> ... std::this_thread::sleep_for(std::chrono::milliseconds(ms)); 

where ms is the amount of time you want to sleep in milliseconds.

You can also replace milliseconds with nanoseconds, microseconds, seconds, minutes, or hours. (These are specializations of the type std::chrono::duration.)

Update: In C++14, if you're sleeping for a set amount of time, for instance 100 milliseconds, std::chrono::milliseconds(100) can be written as 100ms. This is due to user defined literals, which were introduced in C++11. In C++14 the chrono library has been extended to include the following user defined literals:

  • std::literals::chrono_literals::operator""h
  • std::literals::chrono_literals::operator""min
  • std::literals::chrono_literals::operator""s
  • std::literals::chrono_literals::operator""ms
  • std::literals::chrono_literals::operator""us
  • std::literals::chrono_literals::operator""ns

Effectively this means that you can write something like this.

#include <chrono> #include <thread> using namespace std::literals::chrono_literals;  std::this_thread::sleep_for(100ms); 

Note that, while using namespace std::literals::chrono_literals provides the least amount of namespace pollution, these operators are also available when using namespace std::literals, or using namespace std::chrono.

like image 78
Michael Dorst Avatar answered Sep 17 '22 04:09

Michael Dorst