Home > Software design >  Why does the time process to complete the program differ between usleep and sleep in c?
Why does the time process to complete the program differ between usleep and sleep in c?

Time:02-17

#include<stdio.h>
 
main()
{
   printf("Sleep for 5 milisecond to exit.\n");
   sleep(0.005);
   printf("usleep for 5 milisecond to exit.\n");
   usleep(5000);
   return 0;
}

the sleep function takes more time to execute comparatively to the usleep function which takes seconds?

CodePudding user response:

The sleep system call is defined in <unistd.h> on POSIX systems as:

unsigned int sleep(unsigned int seconds);

If you do not include <unistd.h>, the sleep function is not defined and the compiler, using obsolete pre-ansi semantics, infers a prototype of int sleep(double). This has undefined behavior. The actual unsigned int value received by the system could be anything at all, this can cause a long pause as you observe, but it could also crash depending on the system's ABI...

If you include a proper definition by including <unistd.h>, the 0.005 double argument will be implicitly converted to 0 and the program will not pause at all.

Note also that omitting the return type of main() is an obsolete feature. Avoid this old style programming and upgrade your compiler.

It is recommended to enable all warnings to avoid such silly bugs: use the -Wall -Wextra -pedantic options with gcc and clang.

Note also that both sleep and usleep may cause the program to stop for longer than specified in the argument, depending on current system load.

  • Related