1

Is there a function that just sleeps. The amount of time is not an issue. What method should be used so that the computer performance is not disturbed?

user37421
  • 407
  • 1
  • 5
  • 12
  • 2
    Whatever your OS supplies. – ThingyWotsit May 24 '17 at 19:15
  • 1
    Also, the amount of time is usually an issue since the granularity on OS sleep() style calls is in the order of ms. Shorter sleeps are awkward for a general-purpose OS, whereas much longer 'sleeps', ie. in the order of days, are better provided by an out-of-process OS scheduler, eg. like cron or Windows Scheduler. – ThingyWotsit May 24 '17 at 19:19
  • There are many previous questions, [here is one](https://stackoverflow.com/questions/14812233/sleeping-for-milliseconds-on-windows-linux-solaris-hpux-ibm-aix-vxworks-wi) – Weather Vane May 24 '17 at 19:22
  • How do you propose to judge whether or not your chosen method of doing nothing is "efficient"? – Lee Daniel Crocker May 24 '17 at 19:39

2 Answers2

2

Unix variants generally provide sleep(seconds) and usleep(microseconds). usleep() has been deprecated in favor of the POSIX nanosleep(). Windows provides Sleep( sometime_in_millisecs );

Windows:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep( 3000 );   // sleep three seconds
    printf( "sleep ended\n" );
}

Linux (Unix):

#include <unistd.h>

//unsigned int sleep(unsigned int seconds);

int main() {
    sleep( 3 ); // sleep 3 seconds
    usleep( 3000000 ); // sleep 3 seconds more
    return( 0 );
}
Chimera
  • 5,884
  • 7
  • 49
  • 81
1

Presuming you are using Linux platform, there is a standard C function that can sleep for microseconds.

#include <unistd.h>
unsigned int usec;
...
usleep(usec);

When Sleep is called, the program comes out from running state and re-enters to ready state when sleep time gets over, so no impact on CPU time. Other processes/threads may take advantage of CPU by then. If usleep is not available on the Unix variant you use, alternately, you may use sleep is the granularity is in seconds,

unsigned int sleep(unsigned int seconds);
Prithwish Jana
  • 317
  • 2
  • 11
  • `usleep` is not a "standard C function". – Weather Vane May 24 '17 at 19:25
  • 1
    `usleep()` is an obsolete POSIX function; still available in POSIX are [`sleep`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sleep.html), and [`nanosleep`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html). There is also [`thrd_sleep`](http://port70.net/~nsz/c/c11/n1570.html#7.26.5.7) from `threads.h`; standard in C11, but still unsupported in glibc. – ad absurdum May 24 '17 at 20:26