只是在测试这两个小程序,
#include <thread>
int main()
{
for (int i = 0; i < 10000000; i++)
{
std::this_thread::yield();
}
return 0;
}
以及:
#include <thread>
#include <chrono>
int main()
{
using namespace std::literals;
for (int i = 0; i < 10000000; i++)
{
std::this_thread::sleep_for(0s);
}
return 0;
}
我在我的系统上获得了各自的时间(Ubuntu 22.04LTS,内核版本5.19.0-43-Generic),
./a.out 0,33s user 1,36s system 99% cpu 1,687 total
以及:
./a.out 0,14s user 0,00s system 99% cpu 0,148 total
为什么std::this_thread::yield()
比std::this_thread::sleep_for(0s)
慢10倍?
注:g++和clang++之间的时序相似.
编辑:正如答案中指出的,这是对STL实现的优化,调用sleep(0)
实际上要慢300倍(50us对150 ns).