【问题标题】:Using thrust::max_element in a CUDA C project在 CUDA C 项目中使用推力::max_element
【发布时间】:2016-03-08 02:21:00
【问题描述】:

在 CUDA C 项目中,我想尝试使用 Thrust 库来查找浮点数组中的最大元素。似乎推力函数推力::max_element() 是我需要的。我想在其上使用此函数的数组是 cuda 内核的结果(似乎工作正常),因此在调用推力::max_element() 时它已经存在于设备内存中。 我对 Thrust 库不是很熟悉,但是在查看了thrust::max_element() 的文档并阅读了该站点上类似问题的答案后,我想我已经掌握了这个过程的工作原理。不幸的是,我得到了错误的结果,而且似乎我没有正确使用库函数。有人可以告诉我我的代码有什么问题吗?

float* deviceArray;
float* max;
int length = 1025;

*max = 0.0f;
size = (int) length*sizeof(float);     

cudaMalloc(&deviceArray, size);
cudaMemset(deviceArray, 0.0f, size);

// here I launch a cuda kernel which modifies deviceArray

thrust::device_ptr<float> d_ptr = thrust::device_pointer_cast(deviceArray);
*max = *(thrust::max_element(d_ptr, d_ptr + length));

我使用以下标题:

#include <thrust/extrema.h>
#include <thrust/device_ptr.h>

即使我确信在运行内核后 deviceArray 包含非零值,我仍不断得到 *max 的零值。 我使用 nvcc 作为编译器 (CUDA 7.0),并且在计算能力为 3.5 的设备上运行代码。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: cuda max thrust


    【解决方案1】:

    这不是正确的 C 代码:

    float* max;
    int length = 1025;
    
    *max = 0.0f;
    

    在您正确地为该指针提供分配(并将指针设置为等于该分配的地址)之前,您不得使用指针 (max) 存储数据。

    除此之外,您的其余代码似乎对我有用:

    $ cat t990.cu
    #include <thrust/extrema.h>
    #include <thrust/device_ptr.h>
    #include <iostream>
    
    
    int main(){
    
      float* deviceArray;
      float max, test;
      int length = 1025;
    
      max = 0.0f;
      test = 2.5f;
      int size = (int) length*sizeof(float);
    
      cudaMalloc(&deviceArray, size);
      cudaMemset(deviceArray, 0.0f, size);
      cudaMemcpy(deviceArray, &test, sizeof(float),cudaMemcpyHostToDevice);
    
      thrust::device_ptr<float> d_ptr = thrust::device_pointer_cast(deviceArray);
      max = *(thrust::max_element(d_ptr, d_ptr + length));
      std::cout << max << std::endl;
    }
    $ nvcc -o t990 t990.cu
    $ ./t990
    2.5
    $
    

    【讨论】:

    • 感谢您的回答。是的,很抱歉变量声明部分的C代码不正确,我没有想太多就写了。正如您可能已经想象的那样,我在这里报告的代码是更大脚本的一部分,并且一开始的错误部分是试图合成不同的东西,但我想写一些东西是为了完整性。不幸的是,我做得太匆忙了。无论如何,再次感谢你向我展示这个工作代码:那么我必须假设这个错误在其他地方。
    猜你喜欢
    • 2022-07-28
    • 2017-02-14
    • 2014-07-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2013-01-04
    相关资源
    最近更新 更多