使用C++17的并行算法库加速应用程序

VS2019已经支持C++17标准,在C++17中可以更加轻松的使用并行算法。
在通常情况下,我们一般使用for循环对容器内的值进行计算,例如:

#include <iostream>
#include <vector>
#include <execution>
#include <chrono>

int main()
{
	auto count = std::numeric_limits<int>::max() / (40 * sizeof(int));
	std::vector<int> in(count);
	std::generate(in.begin(), in.end(), []() {return std::rand(); });
	std::vector<int> out(count);

	auto before = std::chrono::system_clock::now();
	for (size_t i = 0; i < in.size(); i++)
	{
		out[i] = in[i] * 10;
	}
	auto after = std::chrono::system_clock::now();
	std::cout << (std::chrono::duration_cast<std::chrono::milliseconds>(after - before)).count()
		<< " ms" << std::endl;
	return 0;
}

在我的计算机上,该运算耗时为:

991 ms

将for循环修改为transform并行算法:

#include <iostream>
#include <vector>
#include <execution>
#include <chrono>

int main()
{
	auto count = std::numeric_limits<int>::max() / (40 * sizeof(int));
	std::vector<int> in(count);
	std::generate(in.begin(), in.end(), []() {return std::rand(); });
	std::vector<int> out(count);

	auto before = std::chrono::system_clock::now();
	std::transform(std::execution::par_unseq, in.begin(), in.end(), out.begin(), [](auto i) {
		return i * 10;
		});
	auto after = std::chrono::system_clock::now();
	std::cout << (std::chrono::duration_cast<std::chrono::milliseconds>(after - before)).count()
		<< " ms" << std::endl;
	return 0;
}

并行后的算法耗时:

67 ms

注意:如果不带std::execution::par_unseq参数,则该算法是串行执行的:

std::transform(in.begin(), in.end(), out.begin(), [](auto i) {
		return i * 10;
		});

C++17中还有许多算法是支持并行执行的。
VS对并行算法的支持情况如下:

C++17 的并行算法库是完整的。 这并不意味着,每种算法在各种情况下都是并行执行的;我们已将最重要的算法并行执行,而且即使算法未并行执行,我们也提供执行策略签名。 实现的中央内部头 yvals_core.h 包含以下“并行算法备注”:C++ 允许将并行算法作为对串行算法的调用来实现。 此实现并行执行几个常见算法调用,但不是全部。
以下算法并行执行:
adjacent_difference、adjacent_find、all_of、any_of、count、count_if、equal、exclusive_scan、find、find_end、find_first_of、find_if、find_if_not、for_each、for_each_n、inclusive_scan、is_heap、is_heap_until、is_partitioned、is_sorted、is_sorted_until、mismatch、none_of、partition、reduce、remove、remove_if、replace、replace_if、search、search_n、set_difference、set_intersection、sort、stable_sort、transform、transform_exclusive_scan、transform_inclusive_scan、transform_reduce
以下算法目前不并行执行:
目标硬件上的并行性能没有显著提升;只用于复制或交换无分支的元素的所有算法通常会受内存带宽限制:
copy, copy_n, fill, fill_n, move, reverse, reverse_copy, rotate, rotate_copy, shift_left, shift_right, swap_ranges
对用户并行性要求存在混淆;可能出现在上述类别中:
generate, generate_n
疑为不可实现的有效并行性:
partial_sort, partial_sort_copy
尚未评估;并行性可能在未来的版本中实现,且可能是有益的:
copy_if、includes、inplace_merge、lexicographical_compare、max_element、merge、min_element、minmax_element、nth_element、partition_copy、remove_copy、remove_copy_if、replace_copy、replace_copy_if、set_symmetric_difference、set_union、stable_partition、unique、unique_copy

原文描述

发布了16 篇原创文章 · 获赞 11 · 访问量 6672

猜你喜欢

转载自blog.csdn.net/oLuoJinFanHua12/article/details/102956896