trm
trm

Reputation: 420

alternative to std::this_thread::sleep_for()

I have a loop and I want to ensure that it runs for an (approximately) fixed amount of time for each loop.

I am using sleep_for to achieve this behavior but I also want the program to be able to compile on environments that do not include full support of the standard thread library. Right now I have something like this:

using namespace std;
using namespace std::chrono;

//
while( !quit )
{
    steady_clock::time_point then = steady_clock::now();

    //...do loop stuff

    steady_clock::time_point now = steady_clock::now();
#ifdef NOTHREADS
    // version for systems without thread support
    while( duration_cast< microseconds >( now - then ).count() < 10000 )
    {
        now = steady_clock::now();
    }

#else
    this_thread::sleep_for( microseconds{ 10000 - duration_cast<microseconds>( now - then ).count() } );
#endif

}

While this allows the program to compile in environments that do not support standard threads, it is also very CPU-intensive as the program checks continually for the time condition rather than waiting until it is true.

My question is: Is there a less resource-intensive way to enable this "wait" behavior using only standard C++ (i.e. not boost) in an environment that does not fully support threads?

Upvotes: 6

Views: 2450

Answers (1)

Alexis Wilke
Alexis Wilke

Reputation: 20818

There are many time based functions, it very much depends on the Operating system you're using.

Microsoft API offers Sleep() (capital S) which gives you a millisecond sleep.

Under Unix (POSIX) you have nanosleep().

I think that these two functions should get you running on most computers.

The implementation would be to use the same loop, but sleep a little inside the while() loop. That will still be a pool like thing, but faster much less CPU intensive.

Also, as n.m. mentioned, select() has that capability. Just a bit more convoluted to implement, but it is expected to return once the time elapsed.

Upvotes: 2

Related Questions