c++c++11

Code generated - usleep vs std::this_thread::sleep_for


I'm trying to evaluate usleep vs std::this_thread::sleep_for and seeing more instructions generated when using std::this_thread::sleep_for vs usleep.

Results here: https://godbolt.org/g/ZyCCmj

int main(int, char**)
{
    std::this_thread::sleep_for(std::chrono::milliseconds{30});
    usleep(30000);
    return 0;
}

I'm seeing < 10 instructions with usleep but > 20 when using std::this_thread::sleep_for.

Is it true to conclude that usleep is much more efficient compared to std::this_thread::sleep_for?


Solution

  • Is it true to conclude that usleep is much more efficient compared to std::this_thread::sleep_for?

    No. In your code above, nanosleep(2) is a system call, usleep(3) is a library function. usleep(3) internally calls nanosleep(2). So if you use usleep(3), you can't see those assembly code in your own program, but they exist inside the library function itself.

    However, if your program is intended to sleep, maybe it's meaningless to discuss the performance of a sleep function.

    Moreover, std::this_thread::sleep_for is more portable, which should be preferred. usleep() is even marked as obsolete in POSIX standard.