And*_*rii 8 c++ parallel-processing multithreading future c++11
我编写了一个程序,用于使用c ++ 0x线程搜索数组中的最大值(用于学习目的).为了实现,我使用了标准线程和未来的类.但是,并行化功能不断显示与非并行化相同或更差的运行时间.
代码如下.我试图将数据存储在一维数组,多维数组中,最后得到几个数组.但是,没有选择取得好成绩.我试图从Eclipse和命令行编译和运行我的代码,仍然没有成功.我也尝试过类似的测试而不使用数组.并行化只提高了20%的速度.从我的角度来看,我运行非常简单的并行程序,没有锁和几乎没有资源共享(每个线程在他自己的数组上运行).什么是瓶颈?
我的机器配备2.2 GHz英特尔酷睿i7处理器和8 GB内存,运行Ubuntu 12.04.
const int n = 100000000;
int a[n], b[n], c[n], d[n];
int find_max_usual() {
int res = 0;
for (int i = 0; i < n; ++i) {
res = max(res, a[i]);
res = max(res, b[i]);
res = max(res, c[i]);
res = max(res, d[i]);
}
return res;
}
int find_max(int *a) {
int res = 0;
for (int i = 0; i < n; ++i)
res = max(res, a[i]);
return res;
}
int find_max_parallel() {
future<int> res_a = async(launch::async, find_max, a);
future<int> res_b = async(launch::async, find_max, b);
future<int> res_c = async(launch::async, find_max, c);
future<int> res_d = async(launch::async, find_max, d);
int res = max(max(res_a.get(), res_b.get()), max(res_c.get(), res_d.get()));
return res;
}
double get_time() {
timeval tim;
gettimeofday(&tim, NULL);
double t = tim.tv_sec + (tim.tv_usec / 1000000.0);
return t;
}
int main() {
for (int i = 0; i < n; ++i) {
a[i] = rand();
b[i] = rand();
c[i] = rand();
d[i] = rand();
}
double start = get_time();
int x = find_max_usual();
cerr << x << " " << get_time() - start << endl;
start = get_time();
x = find_max_parallel();
cerr << x << " " << get_time() - start << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
时间显示,find_max_parralel中的几乎所有时间都被消耗掉了
int res = max(max(res_a.get(), res_b.get()), max(res_c.get(), res_d.get()));
Run Code Online (Sandbox Code Playgroud)
编译命令行
g++ -O3 -std=c++0x -pthread x.cpp
Run Code Online (Sandbox Code Playgroud)
更新.问题解决了.我用同样的测试得到了理想的结果.4个线程提供大约3.3个加速,3个线程提供大约2.5个加速,2个线程几乎理想地具有1.9个加速.我刚刚用一些新的更新重新启动了系统.我没有看到cpu负载和运行porgrams的任何显着差异.
感谢大家的帮助.
inf*_*inf 14
你必须明确设置std::launch::async.
future<int> res_c = async(std::launch::async, find_max, c);
Run Code Online (Sandbox Code Playgroud)
如果省略该标志,std::launch::async | std::launch::deferred则可以选择是否以异步方式或延迟方式启动任务.
当前版本的gcc使用std::launch::deferred,MSVC有一个运行时调度程序,它决定运行时应该如何运行任务.
另请注意,如果您想尝试:
std::async(find_max, c);
Run Code Online (Sandbox Code Playgroud)
这也会阻止,因为析构函数std::future等待任务完成.
| 归档时间: |
|
| 查看次数: |
1081 次 |
| 最近记录: |