Effect of usleep(0) in C++ on Linux

Matt Dunn picture Matt Dunn · Oct 10, 2012 · Viewed 20.8k times · Source

The documentation for usleep states that calling usleep(0) has no effect. However, on my system (RHEL 5.2) running the small snippets of C++ code below, I find that it actually appears to have the same effect as usleep(1). Is this to be expected, and if so, why is there the discrepancy between the documentation and what I see in real life?

Exhibit A

Code:

#include <unistd.h>

int main()
{
    for( int i = 0; i < 10000; i++ )
    {
        usleep(1);
    }
}

Output:

$ time ./test
real   0m10.124s
user   0m0.001s
sys    0m0.000s

Exhibit B

Code:

#include <unistd.h>

int main()
{
    for( int i = 0; i < 10000; i++ )
    {
        usleep(1);
        usleep(0);
    }
}

Output:

$ time ./test
real   0m20.770s
user   0m0.002s
sys    0m0.001s

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 10, 2012

Technically it should have no effect. But you must remember that the value passed is used as a minimum, and not an absolute, therefore the system is free to use the smallest possible interval instead.