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
For more information run the command:
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:
Reporting the time in microseconds
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:
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
:
To compile use the -lboost_thread
and -pthread
flags together, example:
That’s all for today, small daily doses that will always keep us tuned with C++ !