why use usleep and not sleep
Solution 1
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.
Solution 2
The argument to sleep is seconds, the argument to usleep is microseconds. Other than that, I think they're identical.
sleep($n) == usleep($n * 1000000) usleep(25000) only sleeps for 0.025 seconds.
Loay Ashmawy
Last year IoT engineering student at INSA. Currently an IoT intern at CELAD
Updated on June 19, 2022Comments
-
Loay Ashmawy almost 2 years
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
andusleep
use thenanosleep
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 useusleep
? isusleep
more "generic" ? -
DragonLord over 2 yearsSleep starts at 1 second and sleeps for years. usleep is only for sub-second sleeps, and on most systems will reject any requests above 1.0 sec.
-
DragonLord over 2 yearsSleep starts at 1 second and sleeps for years. But is only in increments of whole seconds. usleep is inconveniently defined only for sub-second sleeps, and on most systems will reject any requests above 1.0 sec. nanosleep requires a structure with two slots, the seconds and the subseconds, and so works better for mid-term timing longer than one second.