How to put simple Sleep c++ function togetther

richieking 0 Tallied Votes 2K Views Share

This is a basic CPP sleep fuction. As you can see CPP libs do not come with a time sleep/wait fuction to use
in your code/loop.
So due to boring jurney to Saint Petersburg, i decided to write something/code to give anyone who has been
wondering why CPP does not consist of that function.

The idea is nice because there are at least 5 ways to achieve this results. I always like the easy and straight
forward ones.
Have a look at the code below.

I will starting a QT GUI full tutorials in the next few days. Everything QT So watch out for more this year.
Happy coding.

#include <iostream>
#include <ctime>
using namespace std;

void tsleep(int);

int main(){
    
    for(int d = 0;d<40 ; d++){ // count to 40
       cout <<d<<endl;
       tsleep(1);// 1 for 1 seconds .... 2 for 2 secs etc
      }
    return 0;
    }
    
void tsleep(int x){ 
   time_t  ttime;
   long v = time(&ttime);
   while(true){
   if(time(&ttime)- v == x){  //check with the diff
   v = time(&ttime);  // update v to the current time
   break;  //once the check is true then break
    	}
      }
    }
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For a quick and dirty sleep, that's fine (though not strictly portable). But note that a busy loop will consume vast CPU resources whereas a platform provided sleep typically puts the process/thread truly to sleep so that other processes can get a turn. The great differences in how an OS will handle this is why the language hasn't offered such a feature so far.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem with this implementation is that it requires busy-waiting, something which presents a problem on multi-tasking systems. A proper sleep() function, one which passes control to the system scheduler and allows other processes to run, would not be portable between Windows and the various Unix-like systems.

Moreover, while in practice time_t is almost invariably defined as an integral value holding the seconds since 00:00 1 Jan 1970, the key word here is almost. Officially, there is no fixed meaning of the time_t values; the standard does not require it to match that definition, even if all Unix and Unix-like systems (and most systems that emulate them in the C/C++ libraries, like Windows) actually use it this way.

So why doesn't the standard define time_t's meaning? Simple: the C language (and hence C++) was always intended to be portable to all systems, even minimal ones which don't have things like real-time clocks, or ones whose operating system does not expose compatible time management operations. The C language and libraries have amways been based on the principle of requiring the least possible system support, as the language was, and remains, primarily aimed at system programming, and specifically for implementing operating systems.

While C++ could have extended or replaced the C functions with a more complete DateTime class or classes, to date they haven't done so, largely because C++ generally tries to maintain the C approach of minimal system requirements. While it does not maintain the strict minimalism of C - exceptions and memory management in C++ require considerable support - it generally still avoids defining anything that might not be supported by the average base system.

richieking 44 Master Poster

To Decptikon .. There is no sleep function that is 100% accurate as with your extensive experience in c++ i know you have thought about this million years ago. As you know, the problem consists of various factors. 1. The processes at current operational activities.
2. The size of system memmory 3. The platform and the processor.

I think this is one of the main reason why there is no standard fucntion in the ctime lib.

However like Schol-R-Lea stated, time_t will work on all platform because its low level and built in C as you know.

But for a qucik and dirty stuffs this fuction is ok.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There is no sleep function that is 100% accurate

It really depends on what granularity you're looking for. More precise timing becomes more and more difficult, as you mentioned, for various reasons. However, time_t is only guaranteed to be accurate to the second. clock_t is better, but the granularity varies by implementation.

I'd be vastly more concerned about a busy loop than precision in all but the most extreme of cases.

Ancient Dragon commented: Agree :) +14
triumphost 120 Posting Whiz

As you can see CPP libs do not come with a time sleep/wait fuction to use
in your code/loop.

In C++11:

std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::this_thread::sleep_for(std::chrono::nanoseconds(1000000));
std::this_thread::sleep_for(std::chrono::seconds(1));
std::this_thread::sleep_until(.....);

and so on..

Ancient Dragon commented: Excellent :) +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As triumphost says, the C++ does come with both a sleep_for and a sleep_until function. Of course, these functions cannot come with any kind of standard guarantees about timing or being a busy-wait or not, or anything like that, but it provide the comforting thought that someone better than you spent some time implementing the most optimal sleep function for whatever platform you are using, and that is generally good enough for me.

While C++ could have extended or replaced the C functions with a more complete DateTime class or classes, to date they haven't done so

Yes they have, a few years ago. It's in the chrono header. It doesn't exactly go as far as doing "date", it only does "time". For dates, you would have to either rely on the legacy C time library or rely on boost gregorian.

Schol-R-LEA commented: Ah, I wasn't familar with <chrono>. I'll have to read up on that. Thank you. +10
richieking 44 Master Poster

To Deceptikon:
Yes you are right. The idea here was to give insight of how to write a sleep timing. clock_t is also a good idea but as you said its about choice and intended operation.

To triumphost:
The C++11 is not strictly supported unless you indicate the falg for c++11 in the compiler& the linker. That is not currently fully supported universally. But this thread convenient sleep functions are around before C++11 in the boost libs. This tutorial was to give the dity idea how to write sleep on your own. This i intend to give other 4 ways in the coming tutorials. Its about people knowing how things work. Just as there is sort in the algorithm lib but a student can be asked to write their own sort.

To Mike_2000_17:
Yes the chrono currently can do almost all what the C time does. Check it up because its currently the most reliable according to C++ Gurus. The chrono comes with convenient classes like hours,minutes,milliseconds etc. however i think the best way is to mix the standard ctime and the chrono together.

The idea of this tutorial is to give people the idea how to write sleep on their own. just as you can be asked to write sort or other function which already exist. its a tutorial not a cheat code.

I expect people to provide something ... their own style and way to share ideas on that level.

thank you. ))

Assembly Guy 72 Posting Whiz

It really depends on what granularity you're looking for. More precise timing becomes more and more difficult, as you mentioned, for various reasons.

Anyone going to be cheeky and submit a snippet which uses the PIT? Wait, no it wouldn't be portable - it'd be doomed for use on DOS systems and the like ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The idea of this tutorial is to give people the idea how to write sleep on their own. just as you can be asked to write sort or other function which already exist. its a tutorial not a cheat code.

Nobody is dismissing your code as useless. We're simply highlighting issues that anyone who uses it should be aware of.

Here's a portable version that uses time_t:

void s_sleep(double seconds)
{
    time_t start = time(0);

    while (difftime(time(0), start) <= seconds)
        ;
}

You can certainly pass fractions of a second, but there's no guarantee that the timing will be accurate beyond a whole second. The difference is that instead of directly using arithmetic on time_t, difftime handles the comparison portably.

With clock_t, you can get a slightly better result, but it's not portable. However, in practice it's unlikely to fail (which, it's important to note, is the same with time_t):

void ms_sleep(int milliseconds)
{
    clock_t start = clock();
    int clocks_per_ms = CLOCKS_PER_SEC / 1000;

    while (((double)clock() - start) / clocks_per_ms < milliseconds)
        ;
}

For quick and dirty, one of these would be my go to function.

richieking 44 Master Poster

Nice one Deceptikon. The difftime fucntion is one of the tutorial i wanted to show.

Sure its all about having fun and sharing ideas. no matter how trivial it may be. Thanks for your versions. nice stuffs.

with your code... i think there was no need for
int clocks_per_ms = CLOCKS_PER_SEC / 1000; as the
CLOCKS_PER_SEC const value is 1000000 so dividing by 1000 is 1000.Therefore that could have been done like below without the division at all.

void ms_sleep(int milliseconds)
{
    clock_t start = clock();
    int clocks_per_ms = 1000;

    while (((double)clock() - start) / clocks_per_ms < milliseconds)
        ;
}

What is you take about that?

NathanOliver 429 Veteran Poster Featured Poster

I actually prefer seeing int clocks_per_ms = CLOCKS_PER_SEC / 1000; to int clocks_per_ms = 1000;. It lets the person reading the code now exactly what you want to do. Also since it is a constant being divided by a constant it will be optimized away to int clocks_per_ms = 1000; at compile time.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I actually prefer seeing int clocks_per_ms = CLOCKS_PER_SEC / 1000; to int clocks_per_ms = 1000;.

Me too. Too bad CLOCKS_PER_SEC isn't guaranteed to be 1000. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.