最快的方法数2维数组复制到一个一维数组(C语言) [英] Fastest way to copy several 2-dimensional arrays into one 1-dimensional array (in C)

查看:389
本文介绍了最快的方法数2维数组复制到一个一维数组(C语言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲复制的3维阵列的多个2维子阵列(如数组1 [n]的[行] [COLS],...,array4 [n]的[行] [COLS]),这是动态分配(但固定长度),成一维阵列(例如阵列[4 *行* COLS]),它是静态分配,在C作为将有许多行和列(例如,10000行和500列),我想知道其中的以下三种可能性将是最快的:

I want to copy several 2-dimensional subarrays of 3-dimensional arrays (e.g. array1[n][rows][cols], ..., array4[n][rows][cols]), which are dynamically allocated (but with fixed length), into a 1-dimensional array (e.g. array[4*rows*cols]), which is statically allocated, in C. As there will be many rows and columns (e.g. 10000 rows and 500 columns), I was wondering which of the following three possibilities will be the fastest:

    for(i=0;i<rows;i++){
      for(j=0;j<cols;j++){
        array[i*cols+j]=array1[2][i][j];
      }
    }
    ...
    for(i=0;i<rows;i++){
      for(j=0;j<cols;j++){
        array[3*rows*cols+i*cols+j]=array4[2][i][j];
        }
    }

    for(i=0;i<rows;i++){
      for(j=0;j<cols;j++){
        array[i*cols+j]=array1[2][i][j];
      }
      ...
      for(j=0;j<cols;j++){
        array[3*rows*cols+i*cols+j]=array4[2][i][j];
      }
    }

    for(i=0;i<rows;i++){
      for(j=0;j<cols;j++){
        array[i*cols+j]=array1[2][i][j];
        ...
        array[3*rows*cols+i*cols+j]=array4[2][i][j];
      }
    }

还是有甚至在C(不是C ++)?

Or is there even a faster way of performing this task in C (not C++)?

非常感谢! (我想应该已经是一个类似的问题,但遗憾的是没有找到正是我一直在寻找的。所以,我很抱歉,如果我错过了这样一个问题。)

Thanks a lot! (I thought there should be a similar question already, but unfortunately did not find exactly what I was looking for. So, I am sorry if I missed such a question.)

编辑:
之所以希望做,这是以下:具有通过MPI来传达存储在这些2维(子)阵列的信息。这样,客户端将执行上述操作和主(种)的其他方式轮(即1维 - > 2维)。那么,有没有甚至更好的方式来做到这一点的整体?

The reason for wanting to do this is the following: The information stored in those 2-dimensional (sub-)arrays has to be communicated via MPI. So, clients will do the above and the master (kind of) the other way round (i.e. 1-dimensional -> 2-dimensional). So, is there even a better way to do this overall?

推荐答案

假设线性阵列和相同的尺寸(这将作废我的答案):

Assuming linear arrays and the same dimensions (which would invalidate my answer):

for(i=0;i<rows;i++) {
  for(j=0;j<cols;j++) {
    array[i*cols+j]=array1[2][i][j];
  }
}

可以通过以下方式代替:

could be replace by:

memcpy(array, array1[2], sizeof(array1[2]));

因此​​这一个:

Accordingly this one:

for(i=0;i<rows;i++) {
  for(j=0;j<cols;j++) {
    array[3*rows*cols+i*cols+j]=array4[2][i][j];
  }
}

将是:

memcpy(array + 3*cols*rows, array4[2], sizeof(array4[2]));

这篇关于最快的方法数2维数组复制到一个一维数组(C语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆