why use usleep and not sleep

Loay Ashmawy picture Loay Ashmawy · Mar 17, 2017 · Viewed 18.6k times · Source

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" ?

Answer

John Bollinger picture John Bollinger · Mar 17, 2017

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.