CUDA Thrust: Computing finite differences with Thrust

Thrust is a library of parallel algorithms whose routines have been build up so to resemble calls to the C++ Standard Template Library (STL). It is very useful to quickly achieve parallelization with a high level syntax.

By Thrust, legacy (e.g., Matlab written) codes can be easily translated to a CUDA parallel approach. For example, the following Matlab syntax

d_diff2(1:n-2) = d_y(3:n) - 2. * d_y(2:n-1) + d_y(1:n-2);

to calculate second order central differences can be obtained as an application of zip iterators as

struct second_order_central_difference
{

    __host__ __device__ float operator()(thrust::tuple<float,float,float> t)
    {

       float f_1, f0, f1;
       thrust::tie(f_1,f0,f1) = t;
       return f_1 - 2.0f * f0 + f1;
    }

};

thrust::device_vector<float> d_diff2(n-2);

thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(d_y.begin(), d_y.begin() + 1, d_y.begin() + 2)),
           thrust::make_zip_iterator(thrust::make_tuple(d_y.end() - 2, d_y.end() - 1, d_y.end())),
           d_diff2.begin(),second_order_central_difference());

Leave a Reply

Your email address will not be published. Required fields are marked *