CudaSharp —— 在 GPU 上允许你的 C# 代码

来源:互联网 发布:淘宝u站首页在哪里 编辑:程序博客网 时间:2024/06/05 18:51

CudaSharp 项目的目的是让你在支持CUDA的 GPU 上运行 C# 程序。

示例代码:

using System;using CudaSharp;using ManagedCuda;namespace CudaSharpTest{    static class Program    {        static void Main()        {            var ptx = CudaSharp.CudaSharp.Translate<int[]>(kernel);            Test(ptx);            Console.ReadKey(true);        }        static void store(int[] arr, int value)        {            arr[Gpu.ThreadX() + Gpu.BlockX() * Gpu.ThreadDimX()] = value;        }        // ReSharper disable once InconsistentNaming        static void kernel(int[] arr)        {            var tid = Gpu.ThreadX() + Gpu.BlockX() * Gpu.ThreadDimX();            var val = arr[tid];            if (val != 0)                store(arr, val + 3);        }        static void Test(byte[] ptxFile)        {            const int size = 16;            var context = new CudaContext();            var kernel = context.LoadKernelPTX(ptxFile, "kernel");            var memory = context.AllocateMemory(4 * size);            var gpuMemory = new CudaDeviceVariable<int>(memory);            var cpuMemory = new int[size];            for (var i = 0; i < size; i++)                cpuMemory[i] = i - 2;            gpuMemory.CopyToDevice(cpuMemory);            kernel.BlockDimensions = 4;            kernel.GridDimensions = 4;            kernel.Run(memory);            gpuMemory.CopyToHost(cpuMemory);            for (var i = 0; i < size; i++)                Console.WriteLine("{0} = {1}", i, cpuMemory[i]);        }    }

}

转自:http://www.oschina.net/p/cudasharp?utm_source=tuicool&utm_medium=referral

0 0
原创粉丝点击