C++ boost thread delay - c++

I want to wait 1.5 seconds in a boost thread. Using boost::xtime I can wait an integer number of seconds:
// Block on the queue / wait for data for up two seconds.
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec++;
xt.sec++;
....
_condition.timed_wait(_mutex, xt)
How can I wait 1.5 seconds instead?

Would the following not work using the nanoseconds and seconds portion and increasing by 0.5 billion nanoseconds and adding a second which is 1.5 seconds
xt.sec++;
xt.nsec += 500000000;
_condition.timed_wait(_mutex, xt);

Related

API to capture thread's CPU time

I want to measure the CPU time, not elapsed time on a thread. For example, if a thread is waiting or sleeping, it shouldn't count as CPU time because the thread is not in runnable state. So I got the following link to get CPU time. However, it seems to be capturing the elapsed time instead based on my test below (I expect cpu_time_used should be close to 0 but it is actually 2).What am I missing?
https://www.gnu.org/software/libc/manual/html_node/CPU-Time.html
#include <time.h>
clock_t start, end;
double cpu_time_used;
start = clock();
std::this_thread::sleep_for (std::chrono::seconds(2));
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
Note that clock() measures in units of core-time, i.e. CLOCKS_PER_SEC clock() ticks represent one second of computation on one processor, so it indicates the amount of time used by the process over all threads. So, if there is another thread running during the sleep it will still be increasing the clock count -- if there are two threads in total the clock count will indicate 2 seconds have elapsed, like you have shown. If the sleeping thread is the only thread, you get a small amount of time, like #NateEldredge reports. On Linux you can query or setup a timer on CLOCK_THREAD_CPUTIME_ID instead, like #KamilCuk said.

I'm looking to improve or request my current delay / sleep method. c++

Currently I am coding a project that requires precise delay times over a number of computers. Currently this is the code I am using I found it on a forum. This is the code below.
{
LONGLONG timerResolution;
LONGLONG wantedTime;
LONGLONG currentTime;
QueryPerformanceFrequency((LARGE_INTEGER*)&timerResolution);
timerResolution /= 1000;
QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
wantedTime = currentTime / timerResolution + ms;
currentTime = 0;
while (currentTime < wantedTime)
{
QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
currentTime /= timerResolution;
}
}
Basically the issue I am having is this uses alot of CPU around 16-20% when I start to call on the function. The usual Sleep(); uses Zero CPU but it is extremely inaccurate from what I have read from multiple forums is that's the trade-off when you trade accuracy for CPU usage but I thought I better raise the question before I set for this sleep method.
The reason why it's using 15-20% CPU is likely because it's using 100% on one core as there is nothing in this to slow it down.
In general, this is a "hard" problem to solve as PCs (more specifically, the OSes running on those PCs) are in general not made for running real time applications. If that is absolutely desirable, you should look into real time kernels and OSes.
For this reason, the guarantee that is usually made around sleep times is that the system will sleep for atleast the specified amount of time.
If you are running Linux you could try using the nanosleep method (http://man7.org/linux/man-pages/man2/nanosleep.2.html) Though I don't have any experience with it.
Alternatively you could go with a hybrid approach where you use sleeps for long delays, but switch to polling when it's almost time:
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
...
wantedtime = currentTime / timerResolution + ms;
currentTime = 0;
while(currentTime < wantedTime)
{
QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
currentTime /= timerResolution;
if(currentTime-wantedTime > 100) // if waiting for more than 100 ms
{
//Sleep for value significantly lower than the 100 ms, to ensure that we don't "oversleep"
std::this_thread::sleep_for(50ms);
}
}
Now this is a bit race condition prone, as it assumes that the OS will hand back control of the program within 50ms after the sleep_for is done. To further combat this you could turn it down (to say, sleep 1ms).
You can set the Windows timer resolution to minimum (usually 1 ms), to make Sleep() accurate up to 1 ms. By default it would be accurate up to about 15 ms. Sleep() documentation.
Note that your execution can be delayed if other programs are consuming CPU time, but this could also happen if you were waiting with a timer.
#include <timeapi.h>
// Sleep() takes 15 ms (or whatever the default is)
Sleep(1);
TIMECAPS caps_;
timeGetDevCaps(&caps_, sizeof(caps_));
timeBeginPeriod(caps_.wPeriodMin);
// Sleep() now takes 1 ms
Sleep(1);
timeEndPeriod(caps_.wPeriodMin);

sleep the thread using milliseconds instead of using seconds in C++

I have a boost condition variable which I am using to sleep a thread.
boost::condition_variable m_cond;
Currently I am using like this in which I am passing the lock and the seconds to which it has to sleep. Currently it will sleep for 10 seconds
if(!m_cond.timed_wait(lock, boost::posix_time::seconds(10))){
}
Is there any way to do same thing in milliseconds? Instead of passing that as a seconds, can I pass the number of milliseconds it has to wait? Suppose if I need to wait for 2 seconds, then I would like to pass 2000 ms as the value. This doesn't work -
long ms = 2000;
if(!m_cond.timed_wait(lock, ms)){
}
Is there any other way of doing it?
if(!m_cond.timed_wait(lock, boost::posix_time::milliseconds(2000)))

Strange boost::this_thread::sleep behavior

I was trying to implement small time delays in multithreading code using boost::this_thread::sleep.
Here is code example:
{
boost::timer::auto_cpu_timer t;//just to check sleep interval
boost::this_thread::sleep(boost::posix_time::milliseconds(25));
}
Output generated by auto_cpu_timer confused me little bit:
0.025242s wall, 0.010000s user + 0.020000s system = 0.030000s CPU (118.9%)
Why it 0.025242s but not 0.0025242s ?
Because 25 milliseconds is 0.025 seconds; 0.0025 seconds would be 2.5 milliseconds.

sleep for many days with resolution of microseconds

Is there a way to put a thread to sleep for many days with a resolution of microseconds? usleep can only put the thread to sleep for 1000000 and sleep works in second steps. Is there a way to, may be, use both sleep and usleep to achieve this?
While it is not yet time to wake up:
Check the current time
Go to sleep a bit shorter than when you want to wake up.
This way, you can periodically check the time, increasingly faster and more detailed as you reach the time you want to wake up.
Just divide the large sleep in several small sleep periods.
int64_t time_to_sleep = ...;
int peroid_to_sleep = ...;
while( time_to_sleep > 0 )
{
usleep( period_slept );
time_to_sleep -= period_slept;
}