zoukankan      html  css  js  c++  java
  • 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上运行:

  • 相关阅读:
    一本通1590恨 7 不成妻
    一本通1591数字计数
    一本通1589不要 62
    一本通1588数字游戏
    一本通1587【例 3】Windy 数
    一本通1586【 例 2】数字游戏
    一本通1585【例 1】Amount of Degrees
    一本通1584骑士
    一本通1583叶子的染色
    一本通1581旅游规划
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/13286890.html
Copyright © 2011-2022 走看看