Sign in to follow this  
Yourself

C++ : data alignment

Recommended Posts

Yourself    1961
hi, If you want to align data during an optimization of a (C++) program, But should I align to (2^n) or to ((2^n)-1) ?? My structure has at the moment a size of 24, so I want to align it to 32, or should I start counting from zero and align it to 31?? cheers

Share this post


Link to post
Share on other sites
If your struct only has "normal" (that is, no SSE) members, then aligning to 24 bytes will be enough, too. The largest "normal" datatype is 8 bytes, which works fine with 24 (and all others do anyway).
This will likely be good in respect of cache lines too. I am saying "likely" because some CPUs have a problem doing a single load/store across a cache line boundary, and I don't know what your struct looks like. If your struct is layed out the way it should be for normal aligned access, then no problem should occur in any case, it will fit evenly with the typical 32 byte cache lines. But if your layout is bad, you might get misaligned cache access in addition to misaligned access. Therefore, I'm careful saying something without having seen the struct.
On the other hand, having your data in less cache lines is obviously better, especially since the total number of cache lines is limited, and since the first 8 bytes of the struct are guaranteed to be available "instantly", and the CPU is likely to prefetch the next line while you're walking across the current one.

Preferrably, you should use _mm_malloc/_mm_free (for intel or gcc) or _aligned_malloc/_aligned_free (for Microsoft) with an alignment parameter of 24 (which will take care of the low level pointer whacking stuff) and allocate an array of structs for the sake of efficiency, rather than one by one.
If you allocate your structs on the stack, you'd use the respective __attribute__ or __declspec, of course.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this