2

I want to measure how inaccurate usleep can be. I mean , if i write in my program usleep(5000) what is the maximum time the sleep will be?

thanks in advance

kakush
  • 3,334
  • 14
  • 47
  • 68
  • It depends on your system's time resolution. – Mischa Arefiev Jan 23 '12 at 11:14
  • And I assume the system's time resolution is the amount of time in a jiffie? If so, and a jiffie is 1 millisecond on my platform, and I usleep() for 500 microseconds, does that mean I will delay for at least 1 millisecond? – John Mar 05 '14 at 17:37

2 Answers2

4

Unless you have a RTOS kernel, the maximum time is forever.

usleep (or nanosleep or whatever sleep) guarantees to wait for at least as long as you tell it to, rounded to the system timer granularity, unless a signal is caught. You know whether a signal occurred from the return value.

After that time, your thread will be ready to run, and it will run again, eventually, at the scheduler's discretion. Depending on a thousand factors that you don't know, this might be the next nanosecond or in 5 minutes, or never.

Damon
  • 67,688
  • 20
  • 135
  • 185
  • While technically correct, this is a worthless answer. 99.9% of people care about the 99.9% case, not about the theoretical limit. – minexew Dec 18 '16 at 14:17
  • 2
    @minexew: 99.9% of people never use sleep in any program _at all_ because it is almost always wrong. The OP is apparently not only one of the 0.01% who do, but also one of the 0.01% of people who do care about the worst case (hence the question!). Also, note that the lower limit ("undersleeping") is equally important and affects a lot more people than are aware of it. Hardly anyone ever checks the return value (same is true e.g. for the return value of `close`, which is similarly troublesome). – Damon Dec 20 '16 at 09:27
3

usleep on modern Linux systems uses the nanosleep system call, therefore it does not suffer from the signal-related issues of older implementations. On the other hand, it's still affected by the timer resolution of your system, which is kernel and hardware specific.

That said, from the usleep manual page:

POSIX.1-2001 declares this function obsolete; use nanosleep(2) instead. POSIX.1-2008 removes the specification of usleep().

thkala
  • 84,049
  • 23
  • 157
  • 201