Sleep function in C++ - c++

Is there a function like Sleep(time); that pauses the program for X milliseconds, but in C++?
Which header should I add and what is the function's signature?

Use std::this_thread::sleep_for:
#include <chrono>
#include <thread>
std::chrono::milliseconds timespan(111605); // or whatever
std::this_thread::sleep_for(timespan);
There is also the complementary std::this_thread::sleep_until.
Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep function for Windows or Unix:
#ifdef _WIN32
#include <windows.h>
void sleep(unsigned milliseconds)
{
Sleep(milliseconds);
}
#else
#include <unistd.h>
void sleep(unsigned milliseconds)
{
usleep(milliseconds * 1000); // takes microseconds
}
#endif
But a much simpler pre-C++11 method is to use boost::this_thread::sleep.

You'll need at least C++11.
#include <thread>
#include <chrono>
...
std::this_thread::sleep_for(std::chrono::milliseconds(200));

For Windows:
#include "windows.h"
Sleep(10);
For Unix:
#include <unistd.h>
usleep(10)

On Unix, include #include <unistd.h>.
The call you're interested in is usleep(). Which takes microseconds, so you should multiply your millisecond value by 1000 and pass the result to usleep().

Just use it...
Firstly include the unistd.h header file, #include<unistd.h>, and use this function for pausing your program execution for desired number of seconds:
sleep(x);
x can take any value in seconds.
If you want to pause the program for 5 seconds it is like this:
sleep(5);
It is correct and I use it frequently.
It is valid for C and C++.

Prior to C++11, there was no portable way to do this.
A portable way is to use Boost or Ace library.
There is ACE_OS::sleep(); in ACE.

The simplest way I found for C++ 11 was this:
Your includes:
#include <chrono>
#include <thread>
Your code (this is an example for sleep 1000 millisecond):
std::chrono::duration<int, std::milli> timespan(1000);
std::this_thread::sleep_for(timespan);
The duration could be configured to any of the following:
std::chrono::nanoseconds duration</*signed integer type of at least 64 bits*/, std::nano>
std::chrono::microseconds duration</*signed integer type of at least 55 bits*/, std::micro>
std::chrono::milliseconds duration</*signed integer type of at least 45 bits*/, std::milli>
std::chrono::seconds duration</*signed integer type of at least 35 bits*/, std::ratio<1>>
std::chrono::minutes duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
std::chrono::hours duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>

For a short solution use
#include <thread>
using namespace std;
using namespace std::this_thread;
void f() {
sleep_for(200ms);
}

Recently I was learning about chrono library and thought of implementing a sleep function on my own. Here is the code,
#include <cmath>
#include <chrono>
template <typename rep = std::chrono::seconds::rep,
typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
using sleep_duration = std::chrono::duration<long double, std::nano>;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
long double elapsed_time =
std::chrono::duration_cast<sleep_duration>(end - start).count();
long double sleep_time =
std::chrono::duration_cast<sleep_duration>(sec).count();
while (std::isgreater(sleep_time, elapsed_time)) {
end = std::chrono::steady_clock::now();
elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count();
}
}
We can use it with any std::chrono::duration type (By default it takes std::chrono::seconds as argument). For example,
#include <cmath>
#include <chrono>
template <typename rep = std::chrono::seconds::rep,
typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
using sleep_duration = std::chrono::duration<long double, std::nano>;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
long double elapsed_time =
std::chrono::duration_cast<sleep_duration>(end - start).count();
long double sleep_time =
std::chrono::duration_cast<sleep_duration>(sec).count();
while (std::isgreater(sleep_time, elapsed_time)) {
end = std::chrono::steady_clock::now();
elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count();
}
}
using namespace std::chrono_literals;
int main (void) {
std::chrono::steady_clock::time_point start1 = std::chrono::steady_clock::now();
sleep(5s); // sleep for 5 seconds
std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now();
std::cout << std::setprecision(9) << std::fixed;
std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::seconds>(end1-start1).count() << "s\n";
std::chrono::steady_clock::time_point start2 = std::chrono::steady_clock::now();
sleep(500000ns); // sleep for 500000 nano seconds/500 micro seconds
// same as writing: sleep(500us)
std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();
std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count() << "us\n";
return 0;
}
For more information, visit https://en.cppreference.com/w/cpp/header/chrono
and see this cppcon talk of Howard Hinnant, https://www.youtube.com/watch?v=P32hvk8b13M.
He has two more talks on chrono library. And you can always use the library function, std::this_thread::sleep_for
Note: Outputs may not be accurate. So, don't expect it to give exact timings.

I like the solution proposed by #Ben Voigt -- it does not rely on anything outside of C++, but he did not mention an important detail to make the code work. So I am putting the full code, please notice the line starting with using.
#include <thread>
#include <chrono>
...
using namespace std::chrono_literals;
std::this_thread::sleep_for(200ms);

Related

Get timestamp from X milliseconds ago in c++

I'm trying to get the linux timestamp from X milliseconds ago.
I know you can do something like this for seconds:
time_t old_time = difftime(time(nullptr), num_seconds)
However, I'm trying to get the timestamp (aka time from beginning of epoch) in milliseconds, and unfortunately it seems that difftime/time(nullptr) only works in increments of seconds.
I also saw some ideas around using std::chrono::system_clock but I wasn't able to get that to work, something around the way I was casting/etc. is wrong I think.
Here is an example of what I tried (my very first step, doesn't even compile):
Clock::time_point time = Clock::now();
std::chrono::system_clock::duration diff =
std::chrono::duration<int,std::milli>(100);
time = time - diff;
time_t final_timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(time.time_since_epoch()).count();
Does anyone know of an easy solution for this issue? Thanks in advance!
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto old_time = time_point_cast<milliseconds>(system_clock::now()) - 100ms;
std::cout << old_time.time_since_epoch().count() << "ms\n";
}
This gets the current time UTC, truncates it to milliseconds precision, and then subtracts 100ms from that time point.
It then extracts the underlying value and prints it out (milliseconds since 1970-01-01 00:00:00.000 UTC).
This should help out
#include <iostream>
#include <time.h>
using namespace std;
int main(int argc,char** argv){
clock_t start_time = clock();
const long int REPEAT_CYCLES = 500000000;
int result = 0;
for(long int i=0;i<REPEAT_CYCLES;i++)
result = (result > 1000) ? result-1 : result+1;
clock_t finish_time = clock();
cout << "WORK EXECUTION TIME: " << (double)(finish_time - start_time)/1000 << "ms" << endl;
return EXIT_SUCCESS;
}

period must be a specialization of ratio in C++17 chrono library?

I'm clearly too stupid to use the C++17 <chrono> library. Compiling the following...
#include <chrono>
#include <iostream>
int main() {
using clock = std::chrono::steady_clock;
using duration = std::chrono::duration<double, std::chrono::seconds>;
using timepoint = std::chrono::time_point<clock, duration>;
timepoint t0 = clock::now();
for (int i = 0; i < 1000; i++) {
timepoint t = clock::now();
duration d = t-t0;
double seconds = d.count();
std::cout << seconds << std::endl;
}
}
I get...
/usr/include/c++/8/chrono:319:16: error: static assertion failed:
period must be a specialization of ratio
static_assert(__is_ratio<_Period>::value,
^~~~~~~~~~~~~~~~~~~
Any ideas?
The second type parameter to std::chrono::duration needs to be a ratio (ticks per second), not another duration (see https://en.cppreference.com/w/cpp/chrono/duration). std::chrono::seconds is a duration. You'd want this instead:
using duration = std::chrono::duration<double, std::ratio<1> >;
FYI std::chrono::seconds is basically a std::chrono::duration<some integer type, std::ratio<1> >; your duration type is sort of like seconds but with a floating point number instead of an integer.

"storing" a specific time with clock

So I'm wondering if I can use a variable or something and keep the value of clock from when it was stored. So for example :
if (this)
that = Clock();
So then I can do
if (that + 20000)//20 seconds later
dothing();
Any help is greatly appreciated :D
You should look into the std::chrono stuff, it has ways to get the current time, add durations to it, and do all sorts of other wonderful stuff.
For example, something like:
#include <iostream>
#include <chrono>
using namespace std::chrono;
int main() {
auto start = system_clock::now();
while (duration_cast<seconds>(system_clock::now() - start).count() < 5)
;
// It is now 5 seconds later.
}
using sleep_until in c++11
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::seconds sec(2);
std::this_thread::sleep_until(now+sec);
std::cout << " done "<<std::endl;
}

Control loop time with usleep

I try to make sure the execution time of each loop to 10ms with usleep , but sometimes it exceeds 10ms.
I have no idea how to solve this problem, is it proper to use usleep and gettimeofday in this case?
Please help my find out what i missed.
Result: 0.0127289
0.0136499
0.0151598
0.0114031
0.014801
double tvsecf(){
struct timeval tv;
double asec;
gettimeofday(&tv,NULL);
asec = tv.tv_usec;
asec /= 1e6;
asec += tv.tv_sec;
return asec;
}
int main(){
double t1 ,t2;
t1 = tvsecf();
for(;;){
t2= tvsecf();
if(t2-t1 >= 0.01){
if(t2-t1 >= 0.011)
cout << t2-t1 <<endl;
t1 = tvsecf();
}
usleep(100);
}
}
To keep the loop overhead (which is generally unknown) from constantly accumulating error, you can sleep until a time point, instead of for a time duration. Using C++'s <chrono> and <thread> libraries, this is incredibly easy:
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace std;
using namespace std::chrono;
auto t0 = steady_clock::now() + 10ms;
for (;;)
{
this_thread::sleep_until(t0);
t0 += 10ms;
}
}
One can dress this up with more calls to steady_clock::now() in order to ascertain the time between iterations, and perhaps more importantly, the average iteration time:
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace std;
using namespace std::chrono;
using dsec = duration<double>;
auto t0 = steady_clock::now() + 10ms;
auto t1 = steady_clock::now();
auto t2 = t1;
constexpr auto N = 1000;
dsec avg{0};
for (auto i = 0; i < N; ++i)
{
this_thread::sleep_until(t0);
t0 += 10ms;
t2 = steady_clock::now();
dsec delta = t2-t1;
std::cout << delta.count() << "s\n";
avg += delta;
t1 = t2;
}
avg /= N;
cout << "avg = " << avg.count() << "s\n";
}
Above I've added to the loop overhead by doing more things within the loop. However the loop is still going to wake up about every 10ms. Sometimes the OS will wake the thread late, but next time the loop automatically adjusts itself to sleep for a shorter time. Thus the average iteration rate self-corrects to 10ms.
On my machine this just output:
...
0.0102046s
0.0128338s
0.00700504s
0.0116826s
0.00785826s
0.0107023s
0.00912614s
0.0104725s
0.010489s
0.0112545s
0.00906409s
avg = 0.0100014s
There is no way to guarantee 10ms loop time.
All sleeping functions sleeps for at least wanted time.
For a portable solution use std::this_thread::sleep_for
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
for (;;) {
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds{10});
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = end-start;
std::cout << "Waited " << elapsed.count() << " ms\n";
}
}
Depending on what you are trying to do take a look at Howard Hinnants date library.
From the usleep man page:
The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.
If you need high resolution: with C on Unix (or Linux) check out this answer that explains how to use high resolution timers using clock_gettime.
Edit: As mentioned by Tobias nanosleep may be a better option:
Compared to sleep(3) and usleep(3), nanosleep() has the following
advantages: it provides a higher resolution for specifying the sleep
interval; POSIX.1 explicitly specifies that it does not interact with
signals; and it makes the task of resuming a sleep that has been
interrupted by a signal handler easier.

Printing time in seconds

I am writing a program and attempting to time the number of seconds that passes when a given block of code runs. Afterwards I would like to print the total time it took to run the block of code in seconds. What I have written is:
time_t start = time(0);
// block of code
double seconds_since_start = difftime(time(0), start);
printf("seconds since start: %2.60f\n", seconds_since_start);
I have printf() printing to 60 decimal precision and all of the times still come out to 0.000000...
Is there an error in my time function? I find it hard to believe that the task I am asking to time would not account for any time in 60 decimal precision.
You can use the date and time utilities available in C++11:
#include <chrono>
#include <iostream>
#include <thread>
int main()
{
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(5));
auto end = std::chrono::high_resolution_clock::now();
auto difference = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
std::cout << "Seconds since start: " << difference;
}
The return value from time is an integral number of seconds. Casting to a double won't bring back the fractional seconds that have been lost.
You need a more precise clock function, such as gettimeofday (if you want wall-clock time) or times (if you want CPU time).
On Windows, there's timeGetTime, QueryPerformanceCounter (which Castiblanco demonstrates), or GetSystemTimeAsFileTime.
C++ finally got some standard high-resolution clock functions with C++11's <chrono> header, suggested by chris in the comments.
Actually I prefer to do it with milliseconds, because there are tons of function that can return 0 if you use just seconds, for this reason It's better to use milliseconds.
#include <time.h>
double performancecounter_diff(LARGE_INTEGER *a, LARGE_INTEGER *b){
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return (double)(a->QuadPart - b->QuadPart) / (double)freq.QuadPart;
}
int main()
{
LARGE_INTEGER t_inicio, t_final;
double sec;
QueryPerformanceCounter(&t_inicio);
// code here, the code that you need to knos the time.
QueryPerformanceCounter(&t_final);
sec = performancecounter_diff(&t_final, &t_inicio);
printf("%.16g millisegudos\n", sec * 1000.0);*/
}
return 0;
}
you can use boost::timer
template<typename T>
double sortTime(std::vector<T>& v, typename sort_struct<T>::func_sort f){
boost::timer t; // start timing
f(v);
return t.elapsed();
}
Something like that should work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock_t begin, end;
double time_spent;
begin = clock();
//Do stuff
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%Lf\n",time_spent);
}