I have some big arrays given by MATLAB to C++ (therefore I need to take them as they are) that needs casting and permuting (row-mayor, column mayor issues).
The array, imgaux is double type has size size_proj[0]*size_proj[1]*size_proj[2] and needs to be casted to float, changing some locations of values. A minimal example is as follows:
#include <time.h>
#include <stdlib.h>
int main(void){
int size_proj[3];
size_proj[0] = 512;
size_proj[1] = 512;
size_proj[2] = 360;
size_t num_byte_double = size_proj[0] * size_proj[1] * size_proj[2] * sizeof(double);
size_t num_byte_float = size_proj[0] * size_proj[1] * size_proj[2] * sizeof(float);
double *imgaux = (double*) malloc(num_byte_double);
float* img = (float*) malloc(num_byte_float);
clock_t begin, end;
double time_spent;
begin = clock();
for (int k = 0; k < size_proj[0]; k++)
for (int i = 0; i <size_proj[1]; i++)
for (int j = 0; j < size_proj[2]; j++)
img[i + k*size_proj[1] + j*size_proj[0] * size_proj[1]] = (float)imgaux[k + i*size_proj[0] + j*size_proj[0] * size_proj[1]];
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time permuting and casting the input %f", (float)time_spent);
free(imgaux);
free(img);
getchar();
}
However, this is a huge performance bottleneck, taking up to 6 seconds for big arrays (512*512*300).
I know that if instead of doing the 3D indexing part, I'd be doing
for (int k = 0; k < size_proj[0]*size_proj[1]*size_proj[3]; k++)
img[k]=(float)imgaux[k];
The code would be taking about 0.2 seconds to run. However, I need the "permutation" of the dimensions as in the first code snippet.
Is there a way I can speed up that code while still changing the values of place?