I am trying to understand memory access patterns. My question is simple. Who decides the memory access pattern?
gcc
. Thus, I can set it according to my code.Who decides the memory access pattern?
Mostly; the person who writes the code decides the memory access patterns by the choices they make.
For a silly example; if you decide to iterate through an array (like for(i = 0; i <= size; i++) { do_something(&my_array[i]); }
) then you've caused a nice linear access pattern; and if you decide to iterate through a linked list instead (like while(current != NULL) { do_something(current); current = current->next; }
) then you'll probably have a relatively erratic access pattern.
However; in some cases the compiler/linker may try to optimize the memory access patterns. This mostly only changes the fine details slightly (the exact order of individual reads/writes and not the overall pattern itself), but there are cases where a compiler can do more pronounced optimizations (primarily involving nested loops and arrays).
Note 1: It's likely that the result will be a "virtual memory access pattern". Underneath there will be a full memory hierarchy - the OS will control the mapping of virtual memory to physical memory (and handle things like swap space, etc); and then there will be multiple levels of caches and other "cache like things" built into the hardware. None of this matters. It complicates what is actually being accessed (which part of which cache, or which physical memory, or which part of swap space, or...) but accesses will still occur in the same order (and in the same pattern) regardless of what is actually being accessed.
Note 2: A typical program is rarely a simple/single algorithm. If a program (a web browser, a computer game, a compiler, ...) has hundreds of pieces then the program's access pattern will be some combination of the individual access patterns of each piece.