我已经运行了以下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;
}
答案 0 :(得分:2)
您观察所有0
的原因是您在32 << 20 = 33554432
和0
之间生成了大量随机数,即RAND_MAX
,您正在对它们进行排序,但您只显示32
个。
如Robert Crovella所述,在Windows机器上(OP正在使用Windows),RAND_MAX = 2^15-1 = 32767
。因此,您在33554432
和0
之间生成32767
个整数,这意味着您将在原始数组中拥有大量0
个所有0
1}}在排序数组的第一个32
个数字中。
我个人验证了Windows 32
和64
位计算机,即Windows 32
和64
位系统{{1} }}
再一次,正如罗伯特所指出的,这种影响将在Linux RAND_MAX = 32767
位机器上显示,但在Linux 32
位机器上则不会显示64
,因为在这种情况下, RAND_MAX = 2^31-1
比RAND_MAX
大得多。
根据罗伯特的建议,可以改变指令
32 << 20
到
thrust::host_vector<int> h_vec(32 << 20);
避免所有thrust::host_vector<int> h_vec(min(32 << 20,RAND_MAX));
的节目。