我写的cuda程序

 

#include "stdio.h"
#include "cuPrintf.cu"
#define N 10

 __global__ void add(int *da,int *db,int*dc)

{
  
          int tid=blockIdx.x;
          if(tid<N)
         c[tid]=a[tid]+b[tid];  
 
}
int main()
{     
 int a[N],b[N],c[N];//定义host端的三个数组变量
 int *da,*db,*dc; //定义Debice端的三个数组指针变量

    /* 下面三个语句表示在设备端为三个计算数组分配存储空间*/
 cudaMalloc((void**)&da,N*sizeof(int));
 cudaMalloc((void**)&db,N*sizeof(int));
 cudaMalloc((void**))&dc,N*sizeof(int);
 /*在主机端输入依次输入两个数组变量*/
 printf("please input two arrays:");
 printf("the first array a[N]=");
          for(i=0;i<N)
  scanf("%d",&a[i]);
 printf("/n the second array b[N]=");
          for(i=0;i<N)
  scanf("%d",&b[i]);
 /*将Host段的数组内容传递到Debice端*/
 cudaMemcpy(da,a,N*sizeof(int),cudaHostToDevice);
 cudaMemcpy(db,b,N*sizeof(int),cudaHostToDevice);
 /*执行kernel函数,执行参数必须是设备端的参数,即da,db,dc 不应该是主机端的参数a,b,c*/
 add<<< N, 1 >>>(da,db,dc);
 /*将kernel函数执行后的结果由Device端传到Host端*/
 cudaMemcpy(c,dc,N*sizeof(int),cudaDeviceToHost);

 /*用for循环输出数组c[i]的结果*/
        for(i=0;i<N;i++)
       printf("the final array a[i]",c[i]);
 
 /*释放在Device端分配的显存空间*/
 cudaFree(da);
 cudaFree(db);
 
        return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值