CUDA - push :: sort on device仅返回0

时间:2014-04-22 05:58:01

标签: c++ sorting cuda thrust

我已经运行了以下Thrust示例进行排序。问题是在thrust::sort之后,输出包含所有0

请告诉我这里有什么问题。

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>    
#include <thrust/sort.h>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(void)
{

    thrust::host_vector<int> h_vec(32 << 20);
    thrust::generate(h_vec.begin(), h_vec.end(), rand);


    thrust::device_vector<int> d_vec=h_vec;

    for(int i = 0; i<32;i++)
        cout<<d_vec[i]<<endl;

    cout<<endl<<endl<<endl;
    thrust::sort(d_vec.begin(), d_vec.end());

    for(int i = 0; i<32;i++)
        cout<<d_vec[i]<<endl;

    cout<<endl<<endl<<endl; 

    thrust::copy(d_vec.begin(), d_vec.end(), h_vec.begin());


    for(int i = 0; i<32;i++)
        cout<<h_vec[i]<<endl;


    return 0;
}

1 个答案:

答案 0 :(得分:2)

您观察所有0的原因是您在32 << 20 = 335544320之间生成了大量随机数,即RAND_MAX,您正在对它们进行排序,但您只显示32个。

如Robert Crovella所述,在Windows机器上(OP正在使用Windows),RAND_MAX = 2^15-1 = 32767。因此,您在335544320之间生成32767个整数,这意味着您将在原始数组中拥有大量0个所有0 1}}在排序数组的第一个32个数字中。

我个人验证了Windows 3264位计算机,即Windows 3264位系统{{1} }}

再一次,正如罗伯特所指出的,这种影响将在Linux RAND_MAX = 32767位机器上显示,但在Linux 32位机器上则不会显示64,因为在这种情况下, RAND_MAX = 2^31-1RAND_MAX大得多。

根据罗伯特的建议,可以改变指令

32 << 20

thrust::host_vector<int> h_vec(32 << 20);

避免所有thrust::host_vector<int> h_vec(min(32 << 20,RAND_MAX)); 的节目。