【问题标题】:Using linear index to map to 4D array使用线性索引映射到 4D 数组
【发布时间】:2017-11-06 04:51:25
【问题描述】:

我刚开始使用 CUDA 编程,与普通 CPU 相比,我对速度感到困惑。但是,我现在开始考虑一个简单的逻辑考虑。我在设备代码中,我要检查 4D。我创建了一个 constant 变量,并使用 atomicAdd 通过设备代码在每次迭代中添加。

//get global counter
int global_index = atomicAdd(&counter, 1);

然后我考虑一个 4D 体积,并尝试将线性索引映射到 4D 体积。我知道对于 2D 和 3D,有一种从 1D 索引转换为 3D 映射的有效方法。但是,我不知道这种方法如何扩展到更高的维度。

int x = gcfg->dimlen.x;
int y = gcfg->dimlen.y / x;
int z = gcfg->dimlen.z / gcfg->dimlen.y;
int photons = numberofphotons[1];

这是我的 4 个维度的长度。所以,重申一下我遇到的问题:我有一个索引,我想映射到一个 4D 数组,其长度由上述 4 个维度(x、y、z、光子数)指定

【问题讨论】:

    标签: arrays cuda


    【解决方案1】:

    我不确定我是否理解了您问题中变量的含义,但以下代码适用于第一维长度(x)== 第二维长度(y)== 第三的情况尺寸长度(z)== 4。它将线性索引i 转换为每个维度的索引:first_indexsecond_indexthird_indexfourth_index

    int main()
    {
        int x = 4;
        int y = 4;
        int z = 4;
    
        for (int i = 0; i < 100; i++) {
            int fourth_index = i / (x * y * z);
            int third_index = i % (x * y * z) / (x * y);
            int second_index = i % (x * y * z) % (x * y) / x;
            int first_index = i % (x * y * z) % (x * y) % x;
    
            printf("%d: (%d, %d, %d, %d)\n", i, first_index, second_index, third_index, fourth_index);
        }
    }
    

    或者你可以反过来。

    int main()
    {
        int x = 4;
        int y = 4;
        int z = 4;
    
        for (int i = 0; i < 100; i++) {
            int first_index = i % x;
            int second_index = i / x % y;
            int third_index = i / x / y % z;
            int fourth_index = i / x / y / z;
    
            printf("%d: (%d, %d, %d, %d)\n", i, first_index, second_index, third_index, fourth_index);
        }
    }
    

    【讨论】:

    • 这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多