要解决“并行for_each的第一次运行比普通for_each慢10倍”的问题,可以使用以下解决方法:
std::for_each(data.begin(), data.end(), [](int& element) {
// do something
});
#include
#include
#include
#include
int main() {
std::vector data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 创建线程池
const int threadCount = std::thread::hardware_concurrency();
std::vector threadPool(threadCount);
// 并行for_each操作
std::for_each(std::execution::par_unseq, data.begin(), data.end(), [](int& element) {
// do something
});
// 等待所有线程执行完成
for (auto& thread : threadPool) {
thread.join();
}
return 0;
}
这样可以利用线程池中的线程并行执行for_each操作,提高执行速度。
注意:由于线程的创建和销毁开销较大,因此第一次运行并行for_each可能会比普通for_each慢。在后续的运行中,由于线程池已经创建好,可以重复使用线程,从而提高性能。