首页 > 其他 > 详细

Thrust--self-defined(4)

时间:2020-07-12 10:22:39      阅读:88      评论:0      收藏:0      [点我收藏+]

  最近在学习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上运行:

技术分享图片

Thrust--self-defined(4)

原文:https://www.cnblogs.com/xuelanga000/p/13286890.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!