【问题标题】:c++ AMP library with c#: How to keep data in GPU memory?带有c#的c++ AMP库:如何将数据保存在GPU内存中?
【发布时间】:2016-01-16 23:06:01
【问题描述】:

假设我有一个程序可以生成大的随机填充整数数组,并允许我检查可被用户输入的数字整除的项目数量,为此使用 GPU。
c#代码

[DllImport("AMP.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern int RunTest(int* CPUinput, int length, int num);
static void Main(string[] args)
{
    Random rnd = new Random();
    int[] arr = new int[10000000];
    for (int i = 0; i < arr.Length; i++)
        arr[i] = rnd.Next(1, int.MaxValue);
    fixed (int* arrPtr = &arr[0])
    {
        while (true)
        {
            int num = int.Parse(Console.ReadLine());
            Console.WriteLine($"There are {RunTest(arrPtr, arr.Length, num)} numbers in array divisible by {num}");
        }
    }
}

c++代码

extern "C" { __declspec(dllexport) int RunTest(int* input, int length, int num); }
int RunTest(int* CPUinput, int length, int num)
{
    int CPUresult[1];
    CPUresult[0] = 0;
    array_view<int, 1> GPUinput(length, CPUinput);
    array_view<int, 1> GPUresult(1, CPUresult);
    parallel_for_each(GPUinput.get_extent(), [=](index<1> idx) restrict(amp) {
        if (GPUinput[idx[0]] % num == 0)
            atomic_fetch_inc(&GPUresult[0]);
    });
    GPUinput.discard_data();
    GPUresult.synchronize();
    return CPUresult[0];
}

显然,每次运行测试时都复制数组是个坏主意。事实上,在这种情况下,它是一个瓶颈。如何在多个库调用中将数组存储在 gpu 内存中?

【问题讨论】:

    标签: c# c++ dll gpgpu c++-amp


    【解决方案1】:

    我已经这样做了,但那是很久以前的事了。您可能希望在 C++ CLI 中创建一个包装器并与之互操作,以便您的 C# 代码具有可以维护引用的内容,从而保持分配的 GPU 上的内存。

    以下内容应该可以帮助您入门

    C++/CLI wrapper for native C++ to use as reference in C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 2015-08-13
      相关资源
      最近更新 更多