使用cuda对for循环进行并行的小例子

效果图:
这里写图片描述

#include <iostream>
#include <fstream>
using namespace std;

#include <cuda_runtime.h>

__global__ void
GetImage(int* imagedata,const int nx, const int ny,int tempj){
    int i = threadIdx.x;
    int j = blockIdx.x;
    //从左到右,红色通道值增加
    float r = float(i) / float(nx);
    //从上到下,绿色通道值减小
    float g = float(j) / float(ny);
    //蓝色通道值不变
    float b = 0.2f;
    int ir = int(255.99f*r);
    int ig = int(255.99f*g);
    int ib = int(255.99f*b);
    imagedata[j * 800*3 + i * 3] = ir;
    imagedata[j * 800 * 3 + i * 3 + 1] = ig;
    imagedata[j * 800 * 3 + i * 3 + 2] = ib;
}

int main()
{
    int nx = 800;
    int ny = 400;

    int* d_imagedata = NULL;
    cudaMalloc((void**)&d_imagedata, nx*ny*sizeof(int)*3);
    cudaMemset((void**)&d_imagedata, 0, nx*ny*sizeof(int)* 3);

    int threadPerBlock = 400;
    int blockPerGrid = 2;
    dim3  grid(400, 1, 1);
    dim3  threads(800, 1, 1);
    //for (int j = ny - 1; j >= 0; j--)
    {
        GetImage << <grid, threads >> >(d_imagedata, nx, ny, 1);
    }

    int* h_imagedata = (int*)malloc(nx*ny * 3 * sizeof(int));
    cudaMemcpy(h_imagedata, d_imagedata, nx*ny * 3 * sizeof(int), cudaMemcpyDeviceToHost);

    ofstream outfile;
    outfile.open("IMG.ppm");
    outfile << "P3\n" << nx << " " << ny << "\n255\n";
    for (int j = ny - 1; j >= 0; j--){
        for (int i = 0; i < nx; i++){
            int ir = h_imagedata[j*nx * 3 + i * 3];
            int ig = h_imagedata[j*nx * 3 + i * 3 + 1];
            int ib = h_imagedata[j*nx * 3 + i * 3 + 2];
            outfile << ir << " " << ig << " " << ib << "\n";
        }
    }
    outfile.close();

    free(h_imagedata);
    cudaFree(d_imagedata);
    return 0;
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力减肥的小胖子5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值