Making a code wait for a certain time is a practice used by many programmers.
C++ has multiple ways. In this article we will see some forms for Linux and also for Windows .
We will show 5 examples in each of them for the code to wait 2 seconds in some cases also using microseconds and milliseconds .
unistd.h
This is perhaps the simplest form of all, using the #include <unistd.h>
header
#include <unistd.h>
int main(){
// 2 in sleep seconds
sleep(2);
return 0;
}
For more information run the command:
man 3 sleep
std::chrono
std::chrono
is a flexible collection of types that track time with varying degrees of precision. For this example we will use the function: std::this_thread::sleep_for
, example:
Entering the time in seconds:
#include <chrono>
#include <thread>
int main(){
// 2 in sleep seconds
std::this_thread::sleep_for( std::chrono::seconds(2) );
return 0;
}
Reporting the time in microseconds
#include <chrono>
#include <thread>
int main(){
// 2 000 000 MICROSECONDS of sleep
// equates to 2 seconds
std::this_thread::sleep_for( std::chrono::microseconds( 2000000 ) );
return 0;
}
It is still possible to use: minutes
, milliseconds
and among others.
Windows.h
Only for Windows if you want to create portable solutions, it would be something like this:
#ifdef _WIN32
#define WINDOWS_SYSTEM
#include <Windows.h>
#else
#include <unistd.h>
#endif
int main(){
#ifdef WINDOWS_SYSTEM
Sleep( 2000000 );
#else
usleep( 2000000 );
#endif
return 0;
}
boost
Libraryboost.org is a collection of useful libraries for C++ that makes your code more portable.
Check first if you have it installed on your system, although I find it difficult not to have it, as many things use it.
For this example we use boost::posix_time
:
#include <boost/thread.hpp>
int main(){
// Added waits 2 seconds
// wait 1 second
boost::this_thread::sleep( boost::posix_time::seconds(1) );
// wait 1000 milliseconds = 1 second
boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
return 0;
}
To compile use the -lboost_thread
and -pthread
flags together, example:
g++ -lboost_thread -pthread sleep.cpp
That’s all for today, small daily doses that will always keep us tuned with C++ !