CUDA---Thrust(0)--初始化

1.Thrust library :

  Thrust library 和C++中的STL 十分类似,如果学过和了解STL学起来应该会感觉轻松一些。

2. 学习的初衷:

  笔者很多的项目都是和CUDA GPU 相关的,刚开始的时候笔者都是自己写CUDA kernels,

然而,有些东西完全可以站在巨人的肩膀上完成,这样不仅可以提高效率,还可以节省不少的

编程时间。

3.例子程序:

  例子程序笔者是引用的《Thrust_Quick_Start_Guide》写在博客园上主要是为了以后自己方

便使用。大神可以自动忽略。

  代码:

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <iostream>


int main(void) {

    //H has storage for 4 integers
    thrust::host_vector<int>H(4);

    //initialize individual elements
    H[0] = 14;
    H[1] = 20;
    H[2] = 36;
    H[3] = 46;

    //H.size() returns the size of vector H
    std::cout << "H has size" << H.size() << std::endl;

    //print contents of H
    for (int i = 0; i < H.size(); ++i) {
        std::cout << "H[" << i << "]=" << H[i] << std::endl;
    }

    //resize H
    H.resize(2);

    std::cout << "H now has size" << H.size() << std::endl;

    //copy host_vector H to device vector D
    thrust::device_vector<int>D = H;

    //elements of D can be modified 
    D[0] = 99;
    D[1] = 88;

    //print contents of D
    for (int i = 0; i < D.size(); ++i) {
        std::cout << "D[" << i << "]=" << D[i] << std::endl;
    }

    //H and D are automatically deleted when the function returns

    return 0;
}
View Code

  

  就像这个例子所展示的,“=”操作符可以将数据从host_vector复制的device_vector(反之亦然)

但是,需要注意的是,每次从内存中获取数据,都需要调用cudaMemcpy,这会花费很多时间。

原文地址:https://www.cnblogs.com/xuelanga000/p/13185878.html