How inaccurate cpp's usleep function can be?

7.5k Views Asked by At

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

2

There are 2 best solutions below

2
On

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.

0
On

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().