如何将数组从行顺序重写为列顺序? [英] How to rewrite array from row-order to column-order?

查看:81
本文介绍了如何将数组从行顺序重写为列顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个双重for循环,在这里我同时具有行顺序和列顺序的数组索引,这对性能应该是不利的。

I have this double for-loop, where I have both row-order and column-order array indexing, which should be bad for performance.

  for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {

      /* Column-major order */
      d = array_a[col*height +row];

      if (d < 0) { d = 0; }

      /* Row-major order */
      /* Map from x=0,y=0 at buttom left corner to
         0,0 at top left corner */
      array_b[width*(height-1 -row) + col] = d;

    }
  }

是否有解决方法

当我尝试将最后一个重写为列顺序时,数据变得歪斜。

When I try to rewrite the last to column-order, the data becomes skewed. Can't it be rewritten?

Sandra

推荐答案

永远不会太快,因为您可能会遇到许多高速缓存未命中的情况,您要么必须以较大的间距步入一个矩阵,否则就必须逃避。这里的问题是计算机喜欢连续的内存访问接近在一起,而在您的算法中,由于 col * height 期限。要解决此问题,您可以在for循环之间切换,但是在<$ c $中使用 width *(height-1 -row)术语会遇到相同的问题c> array_b

This is never going to be very fast as you'll probably have a number of cache misses, you'll either have to step to the one matrix with a large pitch or the other, there's no escaping that. The problem here is that a computer likes successive memory accesses to be close together, which in your algorithm is not the case the indexing of array_a skips by height elements at a time due to the col*height term. To fix that you could switch around the for loops, but then you'd have the same problem with the width*(height-1 -row) term in array_b.

您可以重写其中一个数组以匹配另一个数组的顺序,但是那样您会遇到完全相同的问题在执行重写的代码中,因此,这取决于您是否需要对同一数据进行多次此类操作,如果这样做,则首先重写其中描述的类似Poita_的矩阵是有意义的,否则,最好保持算法不变。

You could rewrite one of the arrays to match the ordering of the other, but then you would have the exact same problem in the code which does the rewrite, so it depends on whether you need to do this kind of thing more than once on the same data, if you do, then it makes sense to first rewrite one of the matrices like Poita_ described, otherwise you'd best leave the algorithm as is.

这篇关于如何将数组从行顺序重写为列顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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