C++多线程优化累加器

需求:将一个长度为n的vector中的元素累计起来并返回结果:

#include<iostream>
#include<memory>
#include<vector>
#include<thread>
#include<numeric>
#include<math.h>
#include<time.h>
using namespace std;

template<typename Iterator, typename type>
struct accumulate_block {
	void operator()(Iterator first, Iterator late, type& result) {
		result=std::accumulate(first, late,result);
	}
};

template<typename type>
class parallel_accumulate {
	int min(int a, int b) {
		return a > b ? b : a;
	}
public:
	type operator()(vector<type>& vect, type init, int min_thread = 10) {
		if (!vect.size()) return init;
		auto block_begin = vect.begin();

		unsigned long const max_thread = std::thread::hardware_concurrency();
		unsigned long const num_thread = min(max_thread == 0 ? 2 : max_thread, min_thread);
		unsigned long const block_size = vect.size() / num_thread;


		vector<std::thread> threads(num_thread - 1);
		vector<type> results(num_thread);


		accumulate_block<vector<type>::iterator, type> funs;
		for (unsigned long i = 0; i < threads.size(); i++) {
			auto block_end = block_begin;
			std::advance(block_end, block_size);
			threads[i] = std::thread(
					funs,
					block_begin, block_end, std::ref(results[i])
				);
			block_begin = block_end;
		}
		results.back() = accumulate(block_begin, vect.end(), 0);

		for (int i = 0; i < threads.size(); i++) {
			threads[i].join();
		}
		return std::accumulate(results.begin(), results.end(), init);
	}
};

int main() {
	time_t S, E;
	unsigned int eleNum; cin >> eleNum;
	vector<int> vect;
	vect.reserve(eleNum);

	for (int i = 0; i < eleNum; i++) {
		vect.emplace_back(1);
	}
	cout << "push over" << endl;


	S = clock();
	cout << std::accumulate(vect.begin(), vect.end(), 0) << endl;
	E = clock();
	cout << "用时" << (double)(E - S) / 1000 << endl;


	S = clock();
	cout << parallel_accumulate<int>()(vect, 0) << endl;
	E = clock();
	cout << "用时" << (double)(E - S) / 1000 << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值