C++AMP介绍(一)
最后更新日期:2014-05-02
阅读前提:
环境:Windows 8.1 64bit英文版,Visual Studio 2013 Professional Update1英文版,Nvidia QuadroK600 显卡
内容简介
介绍C++ AMP如何使用加速器(GPU)的并发执行能力。通过两个尽可能简洁的程序,让用户了解到如何把AMP应用到自己的程序开发当中。
正文
C++AMP (C++ Accelerated Massive Parallelism)利用并行硬件(例如独立图形加速卡)的性能,加速你C++程序的执行速度,C++ AMP编程模型包括支持多维数组,索引,内存传输和平铺,包括数学函数库。你可以使用C++ AMP更广泛的控制CPU同GPU之间数据的传递。
C++ AMP要求你的显卡完整支持DirectX11硬件特性。
在Visual Studio上建立Win32 控制台项目,下面是我第一个C++AMP应用程序源代码
- #include "stdafx.h"
-
- #include <amp.h>
- #include <iostream>
- using namespace concurrency;
-
- const int size = 5;
-
- void CppAmpMethod() {
- int aCPP[] = { 1, 2, 3, 4, 5 };
- int bCPP[] = { 6, 7, 8, 9, 10 };
- int sumCPP[size];
-
-
-
-
- array_view<const int, 1> a(size, aCPP);
- array_view<const int, 1> b(size, bCPP);
- array_view<int, 1> sum(size, sumCPP);
-
-
-
- sum.discard_data();
-
- parallel_for_each(
-
-
- sum.extent,
-
-
-
-
-
- [=](index<1> idx) restrict(amp)
- {
-
-
- sum[idx] = a[idx] + b[idx];
- }
- );
-
-
- for (int i = 0; i < size; i++) {
- std::cout << sum[i] << "\n";
- }
-
-
- sum.synchronize();
-
-
- for (int i = 0; i < size; i++) {
- std::cout << sumCPP[i] << "\n";
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- CppAmpMethod();
-
- system("pause");
-
- return 0;
- }
第二个C++ AMP程序演示如何自己编写带restrict(amp)修饰的函数,以及如何调用它。
- #include "stdafx.h"
-
- #include <amp.h>
- #include <amp_math.h>
- #include <iostream>
- using namespace concurrency;
-
- const int size = 5;
-
-
-
- void AddElementsWithRestrictedFunction(
- index<1> idx, array_view<int, 1> sum, array_view<int, 1> a, array_view<int, 1> b) restrict(amp)
- {
- sum[idx] = a[idx] + b[idx];
- }
-
-
- void AddArraysWithFunction() {
-
- int aCPP[] = { 1, 2, 3, 4, 5 };
- int bCPP[] = { 6, 7, 8, 9, 10 };
- int sumCPP[5];
-
- array_view<int, 1> a(5, aCPP);
- array_view<int, 1> b(5, bCPP);
- array_view<int, 1> sum(5, sumCPP);
- sum.discard_data();
-
- parallel_for_each(
- sum.extent,
- [=](index<1> idx) restrict(amp)
- {
-
- AddElementsWithRestrictedFunction(idx, sum, a, b);
- }
- );
-
- for (int i = 0; i < 5; i++) {
- std::cout << sum[i] << "\n";
- }
- }
-
-
-
-
-
-
-
-
- void MathExample() {
-
- double numbers[] = { 1.0, 10.0, 60.0, 100.0, 600.0, 1000.0 };
- array_view<double, 1> logs(6, numbers);
-
- parallel_for_each(
- logs.extent,
- [=](index<1> idx) restrict(amp) {
- logs[idx] = concurrency::fast_math::log10(logs[idx]);
- }
- );
-
- for (int i = 0; i < 6; i++) {
- std::cout << logs[i] << "\n";
- }
- }
-
- int _tmain(int argc, _TCHAR* argv[])
- {
-
- AddArraysWithFunction();
-
-
- MathExample();
-
- system("pause");
-
- return 0;
- }
现在你应该已经学会了C++AMP的编程方式,下一篇介绍C++ AMP关于性能优化方面的基本知识。