An effective way to determine the "angle rank" in a flattened multidimensional array

This is a small fragment of a very often called code and part of the convolution algorithm that I am trying to optimize (technically this is my first pass optimization, and I already improved the speed by 2 times, but now I'm stuck):

inline int corner_rank( int max_ranks, int *shape, int pos ) {
  int i;
  int corners = 0;
  for ( i = 0; i < max_ranks; i++ ) {
    if ( pos % shape[i] ) break;
    pos /= shape[i];
    corners++;
  }
  return corners;
}

The code is used to calculate the position property posin an N-dimensional array (which was flattened by a pointer plus arithmetic). max_ranks- dimension, and shape- an array of sizes in each dimension.

An example of a 3-dimensional array may have max_ranks = 3and shape = { 3, 4, 5 }. A schematic arrangement of the first few elements may look like this:

 0       1       2       3       4       5       6       7       8
 [0,0,0] [1,0,0] [2,0,0] [0,1,0] [1,1,0] [2,1,0] [0,2,0] [1,2,0] [2,2,0]

 Returned by function:
 3       0       0       1       0       0       1       0       0

0..8 , pos, . : , , ( 2 12, 24 36).

"" , .

-, , ? % " " - , , .,.

+4
1

, max_ranks, - pos . for-loop. , max_ranks.

, . , , div, @twalberg, .

, 0 ( ), . , . , pos. ; , .

, , . , , .

inline int corner_rank( int max_ranks, int *shape, int pos ) {
  // Most calls will not get farther than this.
  if (pos % shape[0] != 0) return 0;

  // One check here, guarantees that while loop below always returns.
  if (pos == 0) return max_ranks;

  int divisor = shape[0] * shape[1];
  int i = 1;
  while (true) {
    if (pos % divisor != 0) return i;
    divisor *= shape[++i];
  }
}

pos divisor . 255, unsigned char. , , , .

+2

All Articles