fork 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. for (x = 0; x < cols; ++x) // <-- outer
  28. for (y = 0; y < rows; ++y) // <-- inner
  29. printf("(%d, %d) ", x, y);
  30.  
  31. printf("\n\n= COLUMN-MAJOR\n\n");
  32. printf("----\n\n");
  33.  
  34. for (y = 0; y < rows; ++y) // <-- outer
  35. for (x = 0; x < cols; ++x) // <-- inner
  36. printf("(%d, %d) ", x, y);
  37.  
  38. printf("\n\n= ROW-MAJOR\n\n");
  39.  
  40. printf("Therefore the order which best matches the layout of the pixels\n");
  41. printf("in memory (and hence performance due to better cache coherency)\n");
  42. printf("is:\n");
  43. printf(" Outer loop: columns\n");
  44. printf(" Inner loop: rows\n");
  45.  
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 2292KB
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!

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

= COLUMN-MAJOR

----

(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