当前位置:   article > 正文

C++ AMP中GPU并行计算_c++调用显卡计算

c++调用显卡计算

AMP(Gpu并行计算,c#,vc++11) 学习(一)

感觉AMP代码很好懂

一、vc++11代码

#include <amp.h>
  
using namespace concurrency;
 
extern "C" __declspec ( dllexport ) void _stdcall square_array(float* arr, int n)
{
    // Create a view over the data on the CPU
    array_view<float,1> dataView(n, &arr[0]);
  
    // Run code on the GPU
    parallel_for_each(dataView.extent, [=] (index<1> idx) restrict(amp)
    {
        dataView[idx] = dataView[idx] * dataView[idx];
    });
  
    // Copy data from GPU to CPU
    dataView.synchronize();
}

Concurrency是和C#的线程安全数据结构名称一样的。所以很容易理解

parallel_for_each  类似 C#的  Parallel.ForEach

第12行的lambda 更是c#里面天天用的,看到以后很激动


dataView.extend 貌似是需要同时启动的算子数目

[=] 是 [dataView] 的缩写,

 

在c#里面lambda是没有“[]”这个的, []表示要进入lambda函数闭包内的变量。

c#是自动分析的,而vc++11需要手工列出传入的变量。

 

array_view(AMP引用数组)  传值

array 传引用(AMP数组)    (传引用加&)

 

restrict(amp) 是限定这个函数进行语法检查的一个标记,括号里可以写amp 或cpu

如果是amp (GPU)则,函数体里面的内容只能是c++11的一个子集,有些写法是不允许的。具体msdn上有描述

 

函数体不解释。至于Idx可以理解为并行算子的编号。

dataView.synchronize();

将GPU上的数据写回CPU

 

很简单真的,几乎没有一行不明白。

 

===============================================================================

二、c#调用代码
  1. [DllImport("Win32Project1", CallingConvention = CallingConvention.StdCall)]
  2. extern unsafe static void square_array(float* array, int length);
  3. unsafe void Do()
  4. {
  5. // Allocate an array
  6. float[] arr = this.textBox1.Text
  7. .Split(' ')
  8. .Select(v=> Convert.ToSingle(v) ).ToArray();
  9. // Square the array elements using C++ AMP
  10. fixed (float* arrPt = &arr[0])
  11. {
  12. square_array(arrPt, arr.Length);
  13. }
  14. this.textBox2.Text = string.Join(" ", arr);
  15. }

读取textbox的字符串转换为 浮点数组,然后调用amp函数,然后输出到另外一个textBox中。

三、运行效果

image 

四、代码文件

http://files.cnblogs.com/xzbrillia/%E5%AD%A6%E4%B9%A0amp1.rar

五、参考地址

http://blogs.msdn.com/b/pfxteam/archive/2011/09/21/10214538.aspx
 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号