FAQ > Sleeping

Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 2) > Sleeping

This item was added on: 2003/02/22

On occasion, you may want your program to wait for a period of time before continuing, giving the affect of a pause. This can be achieved using a sleep function.

To make a standard sleep function that is portable, you can use the following functions, as supplied by Prelude and Sebastiani. These simply put your program into a permanent loop until the necessary amount of time has passed. The problem with this method is that it is very CPU intensive. For a less CPU intensive, but also less portable method, keep reading.

#include <time.h> 

void sleep_seconds ( long seconds ) {
  clock_t limit, now = clock();
  limit = now + seconds * CLOCKS_PER_SEC;
  while ( limit > now )
    now = clock();

void sleep_ticks ( long ticks ) {
  clock_t limit, now = clock();
  limit = now + ticks;
  while ( limit > now )
    now = clock();

void wait(long milliseconds)
  long timeout = clock() + milliseconds;
  while( clock() < timeout ) continue;

Some compilers come with a non-standard set of functions to do the same thing, but these normally put your program to sleep without the need for a permanent loop. The advantage with these is that they don't hog the CPU.

Check your compiler's documentation for some of these functions:

Sleep() (maybe in windows.h)
sleep() (maybe in unistd.h)
delay() (maybe in dos.h)

Be warned, some functions work in milliseconds, and some in seconds, so handle with care

Script provided by SmartCGIs