fork(1) download
  1. #include <stdio.h>
  2.  
  3. int main(void)
  4. {
  5. int rows = 3, cols = 3;
  6. int x, y;
  7.  
  8. printf("Suppose we have the following bitmap with (x, y) coordinates\n");
  9. printf("where x is the column (HORIZONTAL coordinate)\n");
  10. printf("and y is the row (VERTICAL coordinate)\n");
  11. printf("\n");
  12. printf("(0, 0) (1, 0) (2, 0)\n");
  13. printf("(0, 1) (1, 1) (2, 1)\n");
  14. printf("(0, 2) (1, 2) (2, 2)\n");
  15. printf("\n");
  16. printf("If it is stored in row-major order, then the pixels go from\n");
  17. printf("left to right, top to bottom in memory, in this order:\n");
  18. printf(" \n");
  19. printf("(0, 0) (1, 0) (2, 0) (0, 1) (1, 1) (2, 1) (0, 2) (1, 2) (2, 2) [ROW MAJOR]\n");
  20. printf("\n");
  21. printf("If it is stored in column-major order, then the order is:\n");
  22. printf(" \n");
  23. printf("(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) [COLUMN MAJOR]\n");
  24. printf("\n");
  25. printf("Now let's try it!\n\n");
  26.  
  27. printf("Outer loop = rows, Inner loop = columns:\n\n");
  28. for (x = 0; x < rows; ++x) // <-- outer
  29. for (y = 0; y < cols; ++y) // <-- inner
  30. printf("(%d, %d) ", x, y);
  31.  
  32. printf("\n\n= COLUMN-MAJOR\n\n");
  33. printf("----\n\n");
  34.  
  35. printf("Outer loop = columns, Inner loop = rows:\n\n");
  36. for (y = 0; y < cols; ++y) // <-- outer
  37. for (x = 0; x < rows; ++x) // <-- inner
  38. printf("(%d, %d) ", x, y);
  39.  
  40. printf("\n\n= ROW-MAJOR\n\n");
  41.  
  42. printf("Therefore the order which best matches the layout of the pixels\n");
  43. printf("in memory (and hence performance due to better cache coherency)\n");
  44. printf("is:\n");
  45. printf(" Outer loop: columns\n");
  46. printf(" Inner loop: rows\n");
  47.  
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
Suppose we have the following bitmap with (x, y) coordinates
where x is the column (HORIZONTAL coordinate)
and y is the row (VERTICAL coordinate)

(0, 0)  (1, 0)  (2, 0)
(0, 1)  (1, 1)  (2, 1)
(0, 2)  (1, 2)  (2, 2)

If it is stored in row-major order, then the pixels go from
left to right, top to bottom in memory, in this order:
  
(0, 0) (1, 0) (2, 0) (0, 1) (1, 1) (2, 1) (0, 2) (1, 2) (2, 2)    [ROW MAJOR]

If it is stored in column-major order, then the order is:
  
(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2)    [COLUMN MAJOR]

Now let's try it!

Outer loop = rows, Inner loop = columns:

(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) 

= COLUMN-MAJOR

----

Outer loop = columns, Inner loop = rows:

(0, 0) (1, 0) (2, 0) (0, 1) (1, 1) (2, 1) (0, 2) (1, 2) (2, 2) 

= ROW-MAJOR

Therefore the order which best matches the layout of the pixels
in memory (and hence performance due to better cache coherency)
is:
  Outer loop: columns
  Inner loop: rows