【发布时间】:2023-03-06 03:58:01
【问题描述】:
我在两个程序之间做了一些比较,这些程序用来自 mersenne twister 的伪随机整数填充给定向量,关键是 TBB 版本非常慢,std 版本在大约 0.6 秒内执行任务当 TBB 至少需要 1.1s 时。
我还注意到,TBB 并没有真正提供优化的算法来处理容器,但它只提供通用构造(parallel_for、parallel_for_each 和类似的)来处理通用任务,其中 std 提供 std::generate 更好,而且在这种情况下更清洁的解决方案。
您可以在http://www.sendspace.com/file/ew73h8http://www.sendspace.com/file/ew73h8 下载我的带有 2 个小源文件 + 一个用于 gcc 的 Makefile 的小测试
我在这里做错了什么?我越是增加这个向量的大小,TBB 越慢,我在 Ubuntu 13.04 64 位下使用 Intel Q6600。
TBB 版本在某些方面可能会更好?
编辑:两个文件的完整来源
config.hpp
#define N 10000000
std.cpp
#include <random>
#include <iostream>
#include <vector>
#include <algorithm>
#include "config.hpp"
int main() {
std::vector<u_int32_t> v(N);
std::mt19937 mt;
std::uniform_int_distribution<u_int32_t> dist(0,499);
std::generate(v.begin(),v.end(),[&]{return dist(mt);});
return(0);
}
tbb.cpp
#include <tbb/concurrent_vector.h>
#include <tbb/parallel_for_each.h>
#include <random>
#include <iostream>
#include "config.hpp"
int main()
{
tbb::concurrent_vector<u_int32_t> v(N);
std::mt19937 mt;
std::uniform_int_distribution<u_int32_t> dist(0, 499);
tbb::parallel_for_each(v.begin(),v.end(),[&](u_int32_t& e){e = dist(mt); });
return(0);
}
【问题讨论】:
-
发布问题中的代码。大多数人都不愿意下载未知文件。
-
并解释你的构建/运行环境是什么。如果你只有一个核心,也许加速比低于开销......
-
@Massa 它已经在那里了,我有一个四核 CPU(没有 HT,但我认为这并不重要)
-
@ronag 好的,我已经做到了。
-
std::uniform_int_distribution在多个线程的竞争读取下是否安全?尝试将其设为thread_local,与mt相同。
标签: c++ c++11 vector concurrency tbb