zoukankan      html  css  js  c++  java
  • CUDA--Thrust--带参数自定义函数(6)

      Thrust自定义函数非常灵活,给编写程序带来方便,上次的自定义函数没有带参数,这次

    笔者写一个带参数的自定义函数。通过这次写带参数的自定义函数,我对如何用transformation

    调用函数有了更深的理解。

    代码:

    #include <thrust/device_vector.h>
    #include <thrust/transform.h>
    #include <thrust/sequence.h>
    #include <thrust/copy.h>
    #include <thrust/fill.h>
    #include <thrust/replace.h>
    #include <thrust/functional.h>
    #include <iostream>
    
    #define D_SW 1
    
    
    struct saxpy_functor
    {
        const float a;
        saxpy_functor(float _a) : a(_a) {}
        __host__ __device__
            float operator()(const float& x, const float& y) const {
            return a * x + y;
        }
    };
    
    
    
    void saxpy_fast(float A, thrust::device_vector<float>&X,
        thrust::device_vector<float>&Y) {
        //Y<- A*X+Y
        thrust::transform(X.begin(), X.end(), Y.begin(), Y.begin(),
            saxpy_functor(A));
    
    }
    
    void saxpy_slow(float A, thrust::device_vector<float>&X,
        thrust::device_vector<float>&Y) {
        thrust::device_vector<float>temp(X.size());
    
        //temp=A
        thrust::fill(temp.begin(), temp.end(),A);
    
        //temp=A*X
        thrust::transform(X.begin(), X.end(), temp.begin(), temp.begin(),
            thrust::multiplies<float>());
    
        //Y=A*X+Y
        thrust::transform(temp.begin(), temp.end(), Y.begin(), Y.begin(),
            thrust::plus<float>());
    
    }
    
    int main(void) {
    
        
        float a = -1.0f;
        thrust::device_vector<float>x(10);
        thrust::device_vector<float>y(10);
    
        thrust::sequence(x.begin(), x.end());
        thrust::sequence(y.begin(), y.end());
    
        /*for (int i = 0; i < y.size(); ++i) {
            std::cout << y[i] << std::endl;
        }*/
    #if D_SW
        saxpy_fast(a, x, y);
    #else
        saxpy_slow(a, x, y);
    #endif
        for (int i = 0; i < y.size(); ++i) {
            std::cout << y[i] << std::endl;
        }
    
        return 0;
    }
    function
  • 相关阅读:
    软件架构感悟.
    浏览器缓存技术
    as到底干嘛了???
    关于WebForm开发问题(给新手的建议)
    疑难问题ASP.NET
    破解hash算法.高手请进,求解.
    (MVC和JVPL模式)Moon.Web架构谈
    Moon.NET框架架构及介绍
    调用API设置安卓手机的Access Point
    gtShell 为你常用的目录建立标签并快速跳转
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/13358446.html
Copyright © 2011-2022 走看看