【发布时间】:2021-05-27 07:48:13
【问题描述】:
我希望沿 z 轴对大型 3D 数组进行排序。
示例数组为 X x Y x Z (1000x1000x5)
我想沿 z 轴排序,所以我会沿 z 轴对 5 个元素执行 1000x1000 排序。
编辑更新:尝试在下面使用推力。它很实用,我会将输出存储回来,但这非常慢,因为我在每个 (x,y) 位置一次对 5 个元素进行排序:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <thrust/device_ptr.h>
#include <thrust/sort.h>
#include <thrust/gather.h>
#include <thrust/iterator/counting_iterator.h>
int main(){
int x = 1000, y = 1000, z = 5;
float*** unsorted_cube = new float** [x];
for (int i = 0; i < x; i++)
{
// Allocate memory blocks for
// rows of each 2D array
unsorted_cube[i] = new float* [y];
for (int j = 0; j < y; j++)
{
// Allocate memory blocks for
// columns of each 2D array
unsorted_cube[i][j] = new float[z];
}
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
unsorted_cube[i][j][0] = 4.0f;
unsorted_cube[i][j][1] = 3.0f;
unsorted_cube[i][j][2] = 1.0f;
unsorted_cube[i][j][3] = 5.0f;
unsorted_cube[i][j][4] = 2.0f;
}
}
for (int i = 0; i < 5; i++)
{
printf("unsorted_cube first 5 elements to sort at (0,0): %f\n", unsorted_cube[0][0][i]);
}
float* temp_input;
float* temp_output;
float* raw_ptr;
float raw_ptr_out[5];
cudaMalloc((void**)&raw_ptr, N_Size * sizeof(float));
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
temp_input[0] = unsorted_cube[i][j][0];
temp_input[1] = unsorted_cube[i][j][1];
temp_input[2] = unsorted_cube[i][j][2];
temp_input[3] = unsorted_cube[i][j][3];
temp_input[4] = unsorted_cube[i][j][4];
cudaMemcpy(raw_ptr, temp_input, 5 * sizeof(float), cudaMemcpyHostToDevice);
thrust::device_ptr<float> dev_ptr = thrust::device_pointer_cast(raw_ptr);
thrust::sort(dev_ptr, dev_ptr + 5);
thrust::host_vector<float> host_vec(5);
thrust::copy(dev_ptr, dev_ptr + 5, raw_ptr_out);
if (i == 0 && j == 0)
{
for (int i = 0; i < 5; i++)
{
temp_output[i] = raw_ptr_out[i];
}
printf("sorted_cube[0,0,0] : %f\n", temp_output[0]);
printf("sorted_cube[0,0,1] : %f\n", temp_output[1]);
printf("sorted_cube[0,0,2] : %f\n", temp_output[2]);
printf("sorted_cube[0,0,3] : %f\n", temp_output[3]);
printf("sorted_cube[0,0,4] : %f\n", temp_output[4]);
}
}
}
}
【问题讨论】:
-
嗨,很有趣,不确定这是否有帮助 stackoverflow.com/questions/49818185/…
-
嗨!谢谢你。这是重组数组的一个很好的参考。但是,如果可能的话,我想坚持使用 C++ 来实现它。
-
为每个 (x,y) 坐标生成一个唯一键,用于标记 z 轴子数组进行排序并使用键排序。如果您很聪明,您可能可以使用花哨的迭代器来生成密钥,这样您就不需要将密钥存储在内存中
-
刚刚更新了我的代码,尝试有效,但速度非常慢。我会研究一下钥匙。我不知道该怎么做,但会尝试找到一个例子。任何参考都会很棒......不确定键是如何工作的。
-
无论您的解决方案如何,我认为它不会使用
thrust::sort,因为这是对非常大的列表进行排序。可以通过使用thrust::zip_iterator将所有 5 个值压缩到一个元组中,然后使用thrust::for_each获取 xy 平面中的每个坐标来完成。对于要排序的少量元素,您可以查看此答案,例如stackoverflow.com/a/2748811/10107454(假设您不打算在未来的 z 方向上进行更多切片)。排序算法将是您传递给for_each的一元函数。