cuda 介绍实例

编译玩opencv,我们来说说cuda 的基础以及并行计算的基础,写几个测试程序。
我们为什么采用CPU+GPU架构,总的来说可以获取以下的好处:
1)速度快,采用GPU可以获得CPU的数十倍数百倍的性能,可以实时处理高清图像;
2)成本低,在普通PC机器上插上一块1000多元的Geforce GPU卡即可获得数万元、数十万元高端服务器的性能;
3)减少CPU利用率,提高系统的稳定性。
学cuda 之前,最好会C,因为这两者很相似。
我们用cpu 和cuda 分别去实现两个数组相加求第三个数组的功能。
visual studio 2015 新建一个cuda 程序,我们先用C++ 实现。

#include "stdafx.h"
int main()
{
    const   int arraysize = 5;
    int a[arraysize] = { 1,2,3,4,5 };
    int b[arraysize] = { 10,20,30,40,50 };
    int c[arraysize];
    for (int i = 0; i < arraysize; i++)
    {
        c[i] = a[i] + b[i];
    }    
    printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
        c[0], c[1], c[2], c[3], c[4]);
    getchar();
    return 0;
}

然后用cuda实现:

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
//内核函数
__global__ void addKernel(int *c, const int *a, const int *b)
{//每个线程计算和
    int i = threadIdx.x;
    c[i] = a[i] + b[i];
}

int main()
{//定义三个数组
    const int arraySize = 5;
    const int a[arraySize] = { 1, 2, 3, 4, 5 };
    const int b[arraySize] = { 10, 20, 30, 40, 50 };
    int c[arraySize] = { 0 };
//定义gpu 输入指针
    int *dev_a = 0;
    int *dev_b = 0;
    int *dev_c = 0;
//开辟gpu内存
    cudaMalloc((void**)&dev_c, arraySize * sizeof(int));
    cudaMalloc((void**)&dev_a, arraySize * sizeof(int));
    cudaMalloc((void**)&dev_b, arraySize * sizeof(int));
    // Copy input vectors from host memory to GPU buffers.
    //把a的值传入到dev_a,然后传入gpu内存
    cudaMemcpy(dev_a, a, arraySize * sizeof(int), cudaMemcpyHostToDevice);
    //把b的值传入到dev_b,然后传入gpu内存
    cudaMemcpy(dev_b, b, arraySize * sizeof(int), cudaMemcpyHostToDevice);
    // Launch a kernel on the GPU with one thread for each element.
    //并行运算
    addKernel << <1, arraySize >> >(dev_c, dev_a, dev_b);
    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // Copy output vector from GPU buffer to host memory.
    //把dev_c的值传入到c,然后传入cpu内存
    cudaMemcpy(c, dev_c, arraySize * sizeof(int), cudaMemcpyDeviceToHost);
    printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
        c[0], c[1], c[2], c[3], c[4]);  
    getchar();
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值