当前位置:编程学习 > C#/ASP.NET >>

初探C# GPU通用计算技术

GPU 的并行计算能力高于 CPU,所以最近也有很多利用 GPU 的项目出现在我们的视野中,在 InfoQ 上看到这篇介绍 Accelerator-V2 的文章,它是微软研究院的研究项目,需要注册后才能下载,感觉作为我接触 GPU 通用运算的第一步还不错,于是去下载了回来。

 

在安装包里,包含了几个例子程序,比如著名的 Life 游戏,不过,Life 游戏,相对于刚接触 GPU 运算的我,还是稍显复杂了。于是简化一下,只是进行一些简单的计算,发现,DX9Target.ToArray 如果返回参数是 int 数组的话,则会爆出“未支持的操作”的异常,想想也对,显卡确实是精于浮点运算的。

 

本来,我以为,GPU 运算是 DirectX 11 才有的功能,但是 Accelerator 支持的却是 DirectX 9,想来 DirectX 11 支持的运算能力更高、方式更简单吧。

 

为了简单比较一下 CPU 和 GPU 的速度,也写了一个 .net 4 的并行运算的程序,因为 DX9Target 不支持 int,所以这里的数组也用 float,如下:

 

 

\代码
private const int GridSize = 1024;
private float[] _map;

public Form1()
{
InitializeComponent();
_map = new float[GridSize * GridSize];
for (int y = 0; y < GridSize; y++)
{
for (int x = 0; x < GridSize; x++)
{
_map[x * GridSize + y] = x * y;
}
}
Render();
}

private void Start_Click(object sender, EventArgs e)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
_map = _map.AsParallel().Select(p => p * p * p / 4 + 194).ToArray();
var time = stopwatch.ElapsedMilliseconds;
this.Text = time.ToString();
Render();
}

private void Render()
{
var workingBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);

for (int y = 0; y < pictureBox1.Height; y++)
{
for (int x = 0; x < pictureBox1.Width; x++)
{
workingBitmap.SetPixel(x, y, Color.FromArgb(-0x1000000 | (int)_map[x * 2 * GridSize + y * 2]));
}
}
pictureBox1.Image =<
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,