c++ - 无法理解 CUDA 内核启动的行为

标签 c++ cuda

#include "utils.h"

__global__
void rgba_to_greyscale(const uchar4* const rgbaImage,
                       unsigned char* const greyImage,
                       int numRows, int numCols)
{
  for (size_t r = 0; r < numRows; ++r) {
    for (size_t c = 0; c < numCols; ++c) {
      uchar4 rgba = rgbaImage[r * numCols + c];
      float channelSum = 0.299f * rgba.x + 0.587f * rgba.y + 0.114f * rgba.z;
      greyImage[r * numCols + c] = channelSum;
    }
  }
}

void your_rgba_to_greyscale(const uchar4 * const h_rgbaImage, uchar4 * const d_rgbaImage,
                            unsigned char* const d_greyImage, size_t numRows, size_t numCols)
{
  const dim3 blockSize(1, 1, 1);  //TODO
  const dim3 gridSize( 1, 1, 1);  //TODO
  rgba_to_greyscale<<<gridSize, blockSize>>>(d_rgbaImage, d_greyImage, numRows, numCols);

  cudaDeviceSynchronize(); checkCudaErrors(cudaGetLastError());

}

这是用于将彩色图像转换为灰度图像的代码。我正在为一门类(class)完成这项作业,并在完成它后得到了这些结果。

A.
blockSize = (1, 1, 1)
gridSize = (1, 1, 1)
Your code ran in: 34.772705 msecs.

B.
blockSize = (numCols, 1, 1)
gridSize = (numRows, 1, 1)
Your code ran in: 1821.326416 msecs.

C.
blockSize = (numRows, 1, 1)
gridSize = (numCols, 1, 1)
Your code ran in: 1695.917480 msecs.

D.
blockSize = (1024, 1, 1)
gridSize = (170, 1, 1) [the image size is : r=313, c=557, blockSize*gridSize ~= r*c]
Your code ran in: 1709.109863 msecs.

我已经尝试了更多的组合,但没有一个比 A 获得更好的性能。在将 block 大小和网格大小增加较小的值时,我几乎只有几纳秒的差异。 例如:

blockSize = (10, 1, 1)
gridSize = (10, 1, 1)
Your code ran in: 34.835167 msecs.

我不明白为什么更高的数字不会获得更好的性能,反而会导致更差的性能。此外,似乎增加 block 大小比增加网格大小更好。

最佳答案

您计算启动的每个线程中的所有像素,即内核是完全串行的。使用更多的 block 或更大的 block 只是重复计算。在后一种情况下,为什么不将 for 循环移出内核并让每个线程计算一个像素?

关于c++ - 无法理解 CUDA 内核启动的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414933/

相关文章:

c++ - 设置 MFC 对话框的位置

java - JNI : Calling GetStaticMethodID blows up

c++ - Qt-如何在拖动项目时显示图像/图标/数据?

c++ - 调用 CudaFree 时多线程 CPU CUDA 应用程序不是异步的

c++ - CUDA 矩阵加法段错误

c++ - 为什么线程随机这么慢,-(或者我的代码哪里错了!)

c++ - 将 ActiveX 附加到 win32 应用程序中

我们能否将 CUDA 或 OpenCL 的速度与 CPU 性能进行比较?

c++ - 使用可重定位设备代码时的 CUDA 8.0 Visual Studio 2012 链接器选项

c++ - 预期的 ;在 CUDA 内核上