为什么我的程序在 1 个线程上运行得比在 8 个线程上运行得更快.C++
Why my program runs faster on 1 thread than on 8. C++
请看这个代码:
#include <iostream>
#include <thread>
#include <numeric>
#include <algorithm>
#include <vector>
#include <chrono>
template<typename Iterator, typename T>
struct accumulate_block
{
void operator()(Iterator begin, Iterator end, T& result)
{
result = std::accumulate(begin, end, result);
}
};
template<typename Iterator, typename T>
int accumulate_all(Iterator begin, Iterator end, T& init)
{
auto numOfThreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(numOfThreads);
auto step = std::distance(begin, end) / numOfThreads;
std::vector<int> results(numOfThreads,0);
for(int i=0; i<numOfThreads-1; ++i)
{
auto block_end = begin;
std::advance(block_end, step);
threads[i] = std::thread(accumulate_block<Iterator, T>(), begin, block_end, std::ref(results[i]));
begin = block_end;
}
threads[numOfThreads-1] = std::thread(accumulate_block<Iterator, T>(), begin, end, std::ref(results[numOfThreads-1]));
for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
return accumulate(results.begin(), results.end(), 0);
}
int main()
{
int x=0;
std::vector<int> V(20000000,1);
auto t1 = std::chrono::high_resolution_clock::now();
//std::accumulate(std::begin(V), std::end(V), x); singe threaded option
std::cout<<accumulate_all(std::begin(V), std::end(V), x);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "process took: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanosecondsn";
return 0;
}
当我在并发版本上运行时(基本上在 8 个线程上,因为我的std::thread::hardware_concurrency();
返回 8(
输出为:进程占用:8895404 nanoseconds
。
但单线程选项输出为:process took: 124 nanoseconds
谁能解释这种奇怪的行为??
编译器
删除对std::accumulate
的调用,因为它没有副作用,并且不使用结果。
修复:
auto sum = std::accumulate(std::begin(V), std::end(V), x); // singe threaded option
// At the very end.
std::cout << sum << 'n';
相关文章:
- 为什么std::async使用同一个线程运行函数
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 如何使线程运行现有类的函数?C++
- 使用 4 个和 8 个线程运行时执行的时间相等
- 在我调用join()之前,std ::线程运行
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- 如何确保这部分代码仅由一个线程运行(在 openmp 中)
- 线程连接在另一个线程运行时会导致分段错误
- 动态提升线程运行存储在具有共享指针的向量中的对象的方法
- 如何启动一个 boost::线程运行一个成员函数
- 如果由另一个 OpenMP 程序调用,则外部调用的 OpenMP 程序仅使用一个线程运行
- 线程运行时间最少
- 计算线程运行的次数
- MySQL C API:从不同线程运行查询时出现分段错误
- 使用两个线程运行和中断一个无限循环
- 与icc 14一起使用多线程运行时库时的错误
- 为什么我得到无限循环只有线程# 0后,所有5个线程运行多线程c++用餐哲学家谜语
- 发布配置上的Visual Studio c++多线程运行时问题
- 使用逻辑线程运行程序
- 为什么设置 CPU 关联会使线程运行速度变慢