How can I sleep for less than a second?
The sleep()
function, which is available on all Unixes, only
allows for a duration specified in seconds. If you want finer
granularity, then you need to look for alternatives:
-
Many systems have a functionusleep()
-
You can useselect()
orpoll()
, specifying no file
descriptors to test; a common technique is to write ausleep()
function based on either of these (see the comp.unix.questions FAQ for
some examples)
-
If your system has itimers (most do), you can roll your own
usleep()
using them (see the BSD sources forusleep()
for
how to do this)
-
If you have POSIX realtime, there is ananosleep()
function
Of the above, select()
is probably the most portable (and
strangely, it is often much more efficient than usleep()
or an
itimer-based method). However, the behaviour may be different if signals
are caught while asleep; this may or may not be an issue depending on
the application.
Whichever route you choose, it is important to realise that you may be
constrained by the timer resolution of the system (some systems allow
very short time intervals to be specified, others have a resolution of,
say, 10ms and will round all timings to that). Also, as for
sleep()
, the delay you specify is only a minimum value;
after the specified period elapses, there will be an indeterminate delay
before your process next gets scheduled.
Home | FAQ |