Thrust--self-defined(4)

  最近在学习Thrust库的时候,我发现Thrust可以自定义函数,所以笔者就想自己实现一个功能

通过自己写一个例程来加深对thrust的掌握。在向量的运算中我们会碰见各种范数,我打算以无穷

范数为例,实现这个功能。向量的无穷范数定义为:找出向量中绝对值最大的元素。

代码如下:

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

#include <thrust/extrema.h>
#include <thrust/device_ptr.h>
#include <thrust/device_vector.h>
#include <thrust/functional.h>

#include <stdio.h>

#include<iostream>


#define Size(x) (sizeof(x)/(sizeof(x[0])))

template <typename T>
__host__ __device__ T my_square(T&d_array) {

    return fabs(d_array);
}

struct NormF
{
    __host__ __device__
        float operator()(float &elem) {

        return (my_square(elem));
    }

};

int main(void) {

    float h_a[] = { -1,0,1,3,5,9,10 };
    float *d_a;

    cudaMalloc(&d_a, sizeof(float) *Size(h_a));
    cudaMemcpy(d_a, h_a, sizeof(float) *Size(h_a), cudaMemcpyHostToDevice);

    thrust::device_ptr<float> dev_ptr(d_a);
    thrust::host_vector<float>h_abs(Size(h_a));
    thrust::copy(dev_ptr, dev_ptr + Size(h_a), h_abs.begin());
    thrust::transform(h_abs.begin(), h_abs.end(), h_abs.begin(), NormF());
    float max= *(thrust::max_element(h_abs.begin(), h_abs.end()));
    
    std::cout << "norm infinity=" << max << std::endl;

    return 0;
}
View Code

在vs2017上运行:

posted @ 2020-07-12 03:58  flyingswallow  阅读(151)  评论(0编辑  收藏  举报