将Parralel CUDA程序转换为顺序运行

Converting parralel CUDA program to run sequentially

本文关键字:顺序 运行 程序转换 Parralel CUDA      更新时间:2023-10-16

i具有以下CUDA程序,该程序并行将图像从RGBA转换为Greyscale。我还想有一个版本,该版本将依次运行,这将使我可以比较两者并获得诸如速度等的指标等。

从我的理解中,为了使其顺序运行,我需要以一种将图像使用两个循环(一个用于x,一个用于y)的像素将图像通过像素逐个像素来逐步逐步编辑。然后,应在移动下一个之前,在像素上进行灰度转换。

虽然我对我应该做的事情有一定的了解,但我不确定我应该在哪里编辑代码以及从哪里开始。

编辑:我现在知道这是我需要编辑的内核本身才能使我的程序顺序。

如下所示,

 __global__ void colorConvert(unsigned char * grayImage, unsigned char * rgbImage, unsigned int width, unsigned int height)
{
    unsigned int x = threadIdx.x + blockIdx.x * blockDim.x;
    //unsigned int y = threadIdx.y + blockIdx.y * blockDim.y; //this is needed if you use 2D grid and blocks
    //if ((x < width) && (y < height)) {
    //check if out of bounds
    if ((x < width*height)) {
        // get 1D coordinate for the grayscale image
        unsigned int grayOffset = x;// y*width + x; //this is needed if you use 2D grid and blocks
        // one can think of the RGB image having
        // CHANNEL times columns than the gray scale image
        unsigned int rgbOffset = grayOffset*CHANNELS;
        unsigned char r = rgbImage[rgbOffset]; // red value for pixel
        unsigned char g = rgbImage[rgbOffset + 1]; // green value for pixel
        unsigned char b = rgbImage[rgbOffset + 2]; // blue value for pixel
        // perform the rescaling and store it
        // We multiply by floating point constants
        grayImage[grayOffset] = 0.21f*r + 0.71f*g + 0.07f*b;
    }
}

我已经从问题中删除了其余的代码,因为它也有很多查看。如果我想将此内核以一种顺序运行的方式使用两个用于循环逐步浏览每个像素并将grayImage[grayOffset]代码线应用于每个像素的行?

您需要一个用于循环,使用代码,您可以使用1D数组对所有图像像素,因此您只需要一个。

我认为循环可以像这样编写,以与您的内核相同的参数

for(x=0; x<width*height; ++x)
{
    unsigned int grayOffset = x;
    unsigned int rgbOffset = grayOffset*CHANNELS;
    unsigned char r = rgbImage[rgbOffset]; // red value for pixel
    unsigned char g = rgbImage[rgbOffset + 1]; // green value for pixel
    unsigned char b = rgbImage[rgbOffset + 2]; // blue value for pixel
    // perform the rescaling and store it
    // We multiply by floating point constants
    grayImage[grayOffset] = 0.21f*r + 0.71f*g + 0.07f*b;
}