以下代码不并行运行的原因可能是什么?
#include <iostream>
#include <execution>
#include <unistd.h>
int main() {
std::vector<int> parts(10);
std::iota(parts.begin(), parts.end(), 0);
std::for_each(std::execution::par_unseq,
parts.begin(), parts.end(), [&](int part) {
usleep(1'000'000);
std::cout << part << std::endl;
});
return 0;
}
这是在AMD上运行的Linux Debian,代码是通过以下命令编译的
g++ -std=c++17 -fopenmp -O2 -o test test.cpp
该代码应在大约 1 秒内输出数字 0..9。现在大约需要 10 秒,因为代码不并行运行。
顺便提一句。usleep() 函数可以用其他计算量大的函数替换,但这并不能改变这种情况。