zoukankan      html  css  js  c++  java
  • CUDA并行简单加法

    1. #include<stdio.h>  
    2. #define N 7  
    3. __global__ void add(int *a,int *b,int *c)  
    4. {  
    5.   
    6.     int tid=blockIdx.x;  
    7.     if(tid<N)  
    8.         c[tid]=a[tid]+b[tid];  
    9.   
    10. }  
    11.   
    12. int main()  
    13. {  
    14.     int arr1[N],arr2[N];  
    15.     int sum[N];  
    16.     for(int i=0;i<N;i++)  
    17.     {  
    18.   
    19.         arr1[i]=i;  
    20.         arr2[i]=i+1;  
    21.     }  
    22.     int *a;  
    23.     int *b;  
    24.     int *res;  
    25.     cudaMalloc((void**)&res,sizeof(int)*N);  
    26.     cudaMalloc((void**)&a,sizeof(int)*N);  
    27.     cudaMalloc((void**)&b,sizeof(int)*N);  
    28.     cudaMemcpy(a,arr1,sizeof(int)*N,cudaMemcpyHostToDevice);  
    29.     cudaMemcpy(b,arr2,sizeof(int)*N,cudaMemcpyHostToDevice);  
    30.     //定义N个并行块执行这个函数  
    31.     add<<<N,1>>>(a,b,res);  
    32.     //把结果从device拷贝回host  
    33.     cudaMemcpy(sum,res,sizeof(int)*N,cudaMemcpyDeviceToHost);  
    34.     for(int i=0;i<N;i++)  
    35.         printf("%d ",sum[i]);  
    36.     cudaFree(a);  
    37.     cudaFree(b);  
    38.     //for test  
    39.     scanf("%d",&sum);  
    40.   
    41.   
    42. }  
  • 相关阅读:
    Top WAF
    Access-Control-Allow-Origin与跨域
    SQLlite
    SHell命令总结
    yum仅下载RPM包不安装
    Taglib
    JFinal
    Eclipse maven git
    maven jetty plugin
    wechat
  • 原文地址:https://www.cnblogs.com/honeybusybee/p/4926185.html
Copyright © 2011-2022 走看看