C ++ memory matching

So, I read that when variables are declared in C ++, if you want to get the optimal cache, the memory should adhere to natural alignment. Example:

int a; // memory address should end in 0x0,0x4,0x8,0xC int b[2]; // 8 bytes 0x0,0x8 int b[4]; // 16 bytes 0x0 

But in practice, these variables do not comply with the rules of "natural alignment", the 16-byte variable was located at the memory address that ended with 0xC. Why is this?

+5
source share
4 answers

The priority of natural memory usually refers to the alignment of individual variables, and not to arrays of variables. Thus, an array of 4 byte integers (as you are obviously above) is naturally aligned with a 4 byte boundary, not a 16 byte boundary.

The priority of natural memory usually refers to how the instructions for loading / storing the CPU are archived and implemented, rather than the size of the cache lines. The CPU does not load entire arrays at a time (except for vector loads). Thus, the CPU does not really care if the integer that it loads is part of the array or not.

Vector loads that load small arrays at the same time often have more stringent alignment requirements. For example, to perform an x86 vectorial load, the element must be aligned with 16 bytes.

+4
source

C ++ will not align anything in the cache line, because for all purposes and tasks it does not know that there is a cache.

If you want something aligned on a 16-byte boundary, try posix_memalign() for things on the heap or (if using GCC) on the stack, int x __attribute__ ((aligned (16))) . C ++ 11 has an alignas specifier .

I do not know how to call new() with guaranteed alignment.

+2
source

No leveling guarantee

+1
source

In accordance with the Intel® 64 and IA-32 Architecture Optimization Reference Guide (Help Section B.4.5.2),

The 32-byte AVX storage instructions, which span two pages, require help, which costs approximately 150 cycles.

0
source

All Articles