首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CUDA的推力库处理大值问题

使用CUDA的推力库处理大值问题
EN

Stack Overflow用户
提问于 2011-06-14 15:36:03
回答 1查看 542关注 0票数 0

嗨,我想实现一个推力非常大的循环,但我发现它比正常的C++代码慢得多。你能告诉我我哪里错了吗?fi和fj是宿主载体

xsize通常约为7-8位数字

代码语言:javascript
复制
thrust::host_vector <double> df((2*floor(r)*(floor(r)+1)+1)*n*n); 
thrust::device_vector<double> gpu_df((2*floor(r)*(floor(r)+1)+1)*n*n); 
     for(i=0;i<xsize;i++)
     {
        gpu_df[i]=(fi[i]-fj[i]);

         if(gpu_df[i]<0)
            gpu_df[i]=0;
        else 
       gpu_df[i]=gpu_df[i]*(fi[i]-fj[i]);
        if(gpu_df[i]>255)
            gpu_df[i]=255;
        //      cout<<fi[i]<<"\n";
     }
df=gpu_df;

我觉得代码没有被并行化。你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-15 11:11:16

要在图形处理器上运行具有推力的程序,您需要根据推力算法编写它们,如reducetransformsort等。在这种情况下,我们可以根据transform编写计算,因为循环只是计算函数F(fi[i], fj[i])并将结果存储在df[i]中。请注意,在调用transform之前,我们必须首先将输入数组移动到设备上,因为推力要求输入和输出数组位于同一位置。

代码语言:javascript
复制
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/functional.h>
#include <cstdio>

struct my_functor
  : public thrust::binary_function<float,float,float>
{
  __host__ __device__
  float operator()(float fi, float fj)
      {
    float d =  fi - fj;

    if (d < 0)
      d = 0;
    else
      d = d * d;

    if (d > 255)
      d = 255;

    return d;
  }
};

int main(void)
{
  size_t N = 5;

  // allocate storage on host
  thrust::host_vector<float>   cpu_fi(N);
  thrust::host_vector<float>   cpu_fj(N);
  thrust::host_vector<float>   cpu_df(N);

  // initialze fi and fj arrays
  cpu_fi[0] = 2.0;  cpu_fj[0] =  0.0;
  cpu_fi[1] = 0.0;  cpu_fj[1] =  2.0;
  cpu_fi[2] = 3.0;  cpu_fj[2] =  1.0;
  cpu_fi[3] = 4.0;  cpu_fj[3] =  5.0;
  cpu_fi[4] = 8.0;  cpu_fj[4] = -8.0;

  // copy fi and fj to device
  thrust::device_vector<float> gpu_fi = cpu_fi;
  thrust::device_vector<float> gpu_fj = cpu_fj;

  // allocate storage for df
  thrust::device_vector<float> gpu_df(N);

  // perform transformation
  thrust::transform(gpu_fi.begin(), gpu_fi.end(),  // first input range
                    gpu_fj.begin(),                // second input range
                    gpu_df.begin(),                // output range
                    my_functor());                 // functor to apply

  // copy results back to host
  thrust::copy(gpu_df.begin(), gpu_df.end(), cpu_df.begin());

  // print results on host
  for (size_t i = 0; i < N; i++)
    printf("f(%2.0lf,%2.0lf) = %3.0lf\n", cpu_fi[i], cpu_fj[i], cpu_df[i]);

  return 0;
}

作为参考,下面是程序的输出:

代码语言:javascript
复制
f( 2, 0) =   4
f( 0, 2) =   0
f( 3, 1) =   4
f( 4, 5) =   0
f( 8,-8) = 255
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6340460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档