Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why use usleep and not sleep [closed]

I was reading a code of application and something caught my attention. The code was : usleep(6*1000*1000). I understand that they use this format for readability issues.

I think that both sleep and usleep use the nanosleep function, so my question is: why not using sleep(6) that does exactly the same thing (ie: sleeps for 6 sec) ? Do we gain in performance when we use usleep ? is usleep more "generic" ?

like image 513
Loay Ashmawy Avatar asked Mar 17 '17 15:03

Loay Ashmawy


1 Answers

I think that both sleep and usleep use the nanosleep function,

They may do, or they may not. I'm not aware of any justification in the C and POSIX standards for that supposition.

so my question is: why not using sleep(6) that does exactly the same thing (ie: sleeps for 6 sec) ? Do we gain in performance when we use usleep ? is usleep more "generic" ?

The sleep() function originated in AT&T Unix version 7. The usleep() function originated in BSD 4.3. Although POSIX standardizes a mixture of features drawn from both, there was a time when you were likely to have only one of the two available to you, with which one that was being a function of your particular flavor of Unix.

Nowadays, usleep() is obsolete, and has been removed from POSIX. It's still widely supported, but nanosleep() (or sleep()) should be used instead in new code.

like image 68
John Bollinger Avatar answered Oct 10 '22 07:10

John Bollinger