c++ - 为什么我的程序在 1 个线程上比在 8.C++ 上运行得更快

标签 c++ multithreading c++11 concurrency parallel-processing

请看这段代码:

#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()
    << " nanoseconds\n";
    return 0;
}

当我在并发版本上运行时(基本上是在 8 个线程上,因为我的 std::thread::hardware_concurrency(); 返回 8)
输出是:进程耗时:8895404 纳秒

但是单线程选项输出是:process toked: 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';

关于c++ - 为什么我的程序在 1 个线程上比在 8.C++ 上运行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49978209/

相关文章:

c++ - 将 .txt 文件的内容收集为字符串,C++

Java运行并行程序

.net - 等待异步模式和工作窃取线程

c++ - 如何解压空的可变参数模板列表

c++ - 迁移到 C++11 时出现不等式比较结果未使用警告

linux - 为什么这个 C++11 程序不会死锁?

c++ - 异步串行通信 : why does ReadFile() set the event in the OVERLAPPED struct?

c++ - 我应该如何从循环中跳出?

c++ - 是否可以避免在元组上重复 std::move() ?

Python 多处理和 tkinter - 如何连接此进程(GUI 和衍生进程)?