1

Suppose I have a 3d array A with shape (H, W, C), and the memory storing them is continous, from *p to *(p + H*W*C). I would like to change the layout of the memory storing this array to (C, H, W), which means that the original A[h][w][c] can be accessed with B[c][h][w].

One stupid method is like this:

char* B = new char[H*W*C];
for (int h{0}; h < H; ++h) {
    for (int w{0}; w < W; ++w) {
        for (int c{0}; c < C; ++c) {
            int idx_old = h * H * C + w * C + c;
            int idx_new = c * H * W + h * W + w;
            B[idx_new] = A[idx_old];
        }
    }
}

Is there any c++ built-in function to do this ? Or what is the fastest method to do this with c++ please ?

coin cheung
  • 949
  • 2
  • 10
  • 25
  • Modern compilers are pretty good at optimizations, have you benchmarked (an optimized build) to check that it isn't "good enough™"? Is it a top-three bottleneck in your program? – Some programmer dude Mar 02 '20 at 07:04
  • With my limited knowledege, this looks fine. Node that you could also use the new dimensions `(C,H,W)` order to go through the array. I do not know if this can make any real difference. But this way the writing would be to linear memory, instead of the reading. –  Mar 02 '20 at 07:09

0 Answers0