C ++: comparing the performance of pointers pointing to different locations in a char array (trying to find out the alignment)

Context:

char buffer[99]; int* ptr_int=(int*)(buffer+n);

Then I do some time-consuming operations on * ptr_int and measure the runtime using windows.h / QueryPerformanceCounter.

Confusion: For values ​​n: 0 to 4, the execution time is about 12 seconds. For values ​​n: 5,6,7, the execution time is about 20 seconds. For the value n: 32,33, the execution time is again about 12 seconds.

This may be due to alignment, but can someone explain how exactly?

Pentium with two cores T2410 / winxp / g ++ 3.4.2 (mingw-special)

Edit I am not trying to avoid the alignment problem using the best approaches, instead I am trying to find why I suddenly have an alignment problem withint* ptr_int=(int*)(buffer+5);

No problem with: int* ptr_int=(int*)(buffer+3);ORint* ptr_int=(int*)(buffer+33);

+3
source share
3 answers

On modern processors, the data must be correctly aligned, otherwise hell will pay. A 32-bit integer must be aligned by 4 bytes, otherwise the CPU will internally have to read two integers and move things around to match each other. Some processors actually crash if you try to read an unsigned integer.

Similarly, the 128-bit __vector4 should be aligned to 16 bytes, etc.

, , , - .

+1

. " " .

0

, , . .

- malloc new . Malloc , . 64- Intel , 128- .

char * buffer = malloc( n * sizeof(int) );

int * at = (int*)buffer + ndx;

, +n . , , char ptr, 1 , int ptr, 4 . , . , , .

, , . ,

char cbuffer[1024+sizeof(int)];
int * ibuffer = (cbuffer / sizeof(int) + 1) * sizeof(int);

ibuffer . , cbuffer, ( ). - , , sizeof (int), , .

new: can anyone confirm that it new char[x]also guarantees alignment, like malloc?

0
source

Source: https://habr.com/ru/post/1776632/


All Articles