cuda编程---第一个cuda程序

前言:

1、参考: nvidia offical tutorial

2、使用 nvcc 编译程序,并且加-g -G 参数进行编译,以保存调试信息,之后可以用cuda-gdb 进行单步调试。

程序:

#include <iostream>
#include <math.h>

//CUDA Kernel function to add the elements of two arrays on the GPU.
__global__
void add(int n,float *x, float *y)
{   int index= blockIdx.x*blockDim.x+threadIdx.x;
    int stride=blockDim.x*gridDim.x;
    for(int i=index;i<n;i+=stride)
    y[i]=x[i]+y[i];
}

int main(void){
    int N = 1 << 20; //1M element.

    //float *x=new float[N];
    //float *y=new float[N];

    //Allocate Unified Memory -- accessible from CPU or GPU
    float *x,*y;
    cudaMallocManaged(&x,N*sizeof(float));
    cudaMallocManaged(&y,N*sizeof(float));

    //initialize x and y arrays on the host.
    for (int i=0;i<N;i++){
        x[i]=1.0f;
        y[i]=2.0f;
    }

    int blockSize = 256;
    int numBlocks = (N + blockSize -1) /blockSize;

    //run kernel on 1M elements on the CPU.
    add<<<numBlocks,blockSize>>>(N,x,y);

    //Wait for GPUto finish before accessing on host.
    cudaDeviceSynchronize();

    // Check for errors (all values should be 3.0f)
    float maxError=0.0f;
    for (int i=0;i<N;i++)
        maxError=fmax(maxError,fabs(y[i]-3.0f));
    std::cout << "Max error: " <<maxError<<std::endl;

    //Free memory
    cudaFree(x);
    cudaFree(y);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值