【问题标题】:C++ Cuda performance for double pointers双指针的 C++ Cuda 性能
【发布时间】:2019-05-27 10:58:42
【问题描述】:

我终于成功地在内存中保存了一个双指针,以便在 cuda 中使用它。(下面的代码),但我发现它的性能不如我将矩阵展平,这不是那么好。

一些节省时间/记忆的建议?

我真的很想使用动态二维数组。

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdlib.h>
#include <cstdio>

__global__ void fct(int **dev_c)
{
    int y = threadIdx.x;
    int x = threadIdx.y;
    dev_c[y][x] = 3;
}

int main(void)
{
    //Output Array
    int **cc = new int*[2];
    for (int i = 0; i < 2; i++)cc[i] = new int[2];
    //Host Array
    int ** h_c = (int **)malloc(2 * sizeof(int *));
    for (int i = 0; i < 2; i++) {
        cudaMalloc((void**)&h_c[i], 2 * sizeof(int));
    }
    //Devie array
    int ** d_c;
    cudaMalloc((void **)&d_c, 2 * sizeof(int *));
    cudaMemcpy(d_c, h_c, 2 * sizeof(int *), cudaMemcpyHostToDevice);


    dim3 d(2, 2);
    fct << <1, d >> > (d_c);

    for (int i = 0; i < 2; i++) {
        cudaMemcpy(cc[i], h_c[i], 2 * sizeof(int), cudaMemcpyDeviceToHost);
    }

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("(%d,%d):%d\n", i, j, cc[i][j]);
        }
    }
    int x;
    std::cin >> x;
    delete[] h_c;
    delete[] d_c;
}

【问题讨论】:

  • 如果您在编译时知道二维矩阵的宽度,则可以使用双下标访问(即使在设备代码中),同时仍保持索引访问与双指针访问的性能优势。这个answer 讨论了包括已知宽度方法在内的各种方法。如果您在编译时不知道 2D 矩阵的宽度,我不知道有任何方法可以在每次访问没有 2 个指针取消引用的情况下进行双下标访问。
  • 谢谢!我会记住这一点,但遗憾的是,对于这个项目,我需要该数组是动态的。

标签: c++ pointers cuda


【解决方案1】:

您实际上可能希望通过一些指针技巧来使用扁平矩阵:

int main() {
    const int size = 10;

    auto arr = new int*[size];
    arr[0] = new int[size * size];
    for(int i = 1; i < size; i++) {
        arr[i] = arr[0] + (i * size);
    }
}

这样,您仍然可以使用 arr[x][y] 语法访问矩阵,但实际内存是连续的(这不仅分配速度更快*,而且访问速度更快,因为缓存预取内存在您想要的内存附近使用)。

*分配一次size * size内存比分配sizesize元素快。

旁注:在malloced 内存上使用delete[]未定义的行为。不要将new/new[] + delete/delete[]malloc + free 混用。

【讨论】:

  • 谢谢!不过,如果我想将该 arr 保存在 cuda 内存中,我可以像一个简单的向量一样做到这一点?或者我必须分配每一行?
  • @VladConstantinescu simple vector 是什么意思?
  • 我的意思是,一维数组(int *a = new int[size])
  • 您可以通过传递*arr(或arr[0])将此矩阵作为一维数组传递,如果这是您所要求的。还是有点不清楚。您想将整个矩阵作为单个 1d 数组传递吗?或者你想将单​​行作为一维数组传递?
  • 我想将整个二维矩阵传递给内核函数(fct)。有一种方法我仍然可以在函数内部使用语法矩阵[i][j]?
猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多