gpt4 book ai didi

sorting - CUDA 推力和 sort_by_key

转载 作者:行者123 更新时间:2023-12-01 04:00:59 24 4
gpt4 key购买 nike

我正在 CUDA 上寻找一种排序算法,该算法可以对元素数组 A 进行排序( double )并返回该数组 A 的键 B 数组。
我知道sort_by_key Thrust 库中的函数,但我希望我的元素数组 A 保持不变。
我能做什么?

我的代码是:

void sortCUDA(double V[], int P[], int N) {

real_t *Vcpy = (double*) malloc(N*sizeof(double));
memcpy(Vcpy,V,N*sizeof(double));

thrust::sort_by_key(V, V + N, P);
free(Vcpy);
}

我正在将推力算法与我在顺序 CPU 上的其他算法进行比较
N               mergesort       sortCUDA
113 0.000008 0.000010
226 0.000018 0.000016
452 0.000036 0.000020
905 0.000061 0.000034
1810 0.000135 0.000071
3621 0.000297 0.000156
7242 0.000917 0.000338
14484 0.001421 0.000853
28968 0.003069 0.001931
57937 0.006666 0.003939
115874 0.014435 0.008025
231749 0.031059 0.016718
463499 0.067407 0.039848
926999 0.148170 0.118003
1853998 0.329005 0.260837
3707996 0.731768 0.544357
7415992 1.638445 1.073755
14831984 3.668039 2.150179
115035495 39.276560 19.812200
230070990 87.750377 39.762915
460141980 200.940501 74.605219

推力性能还不错,但我想如果我使用 OMP 可能可以轻松获得更好的 CPU 时间

我认为这是因为 memcpy

解决方案:
void thrustSort(double V[], int P[], int N)
{
thrust::device_vector<int> d_P(N);
thrust::device_vector<double> d_V(V, V + N);
thrust::sequence(d_P.begin(), d_P.end());

thrust::sort_by_key(d_V.begin(), d_V.end(), d_P.begin());

thrust::copy(d_P.begin(),d_P.end(),P);
}

其中 V 是我要排序的双值

最佳答案

您可以修改比较运算符以对键而不是值进行排序。 @Robert Crovella 正确指出无法从主机分配原始设备指针。修改后的算法如下:

struct cmp : public binary_function<int,int,bool>
{
cmp(const double *ptr) : rawA(ptr) { }

__host__ __device__ bool operator()(const int i, const int j) const
{return rawA[i] > rawA[j];}

const double *rawA; // an array in global mem
};

void sortkeys(double *A, int n) {
// move data to the gpu
thrust::device_vector<double> devA(A, A + n);
double *rawA = thrust::raw_pointer_cast(devA.data());

thrust::device_vector<int> B(n);
// initialize keys
thrust::sequence(B.begin(), B.end());
thrust::sort(B.begin(), B.end(), cmp(rawA));
// B now contains the sorted keys
}

这是arrayfire的替代方案。虽然我不确定哪一个更有效,因为 arrayfire 解决方案使用了两个额外的数组:
void sortkeys(double *A, int n) {
af::array devA(n, A, af::afHost);
af::array vals, indices;
// sort and populate vals/indices arrays
af::sort(vals, indices, devA);
std::cout << devA << "\n" << indices << "\n";
}

关于sorting - CUDA 推力和 sort_by_key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com