335 points · by Tsiolkovsky · 12y ago · 143 comments
The reasons you would do it today are different than a decade ago and the rules have changed because the processors have changed. To add two clarifying points to the original article:
- The main reason to do optimal structure packing today is to reduce cache line misses. Because cache line misses are so expensive it is a big net performance gain in many cases to have the code do a little more work if it reduces cache line fills; optimal structure packing is basically a "free" way of minimizing cache misses.
- On modern Intel microarchitectures, alignment matters much less for performance than it used to. One of the big changes starting with the i7 is that unaligned memory accesses have approximately the same cost as aligned memory accesses. This is a pretty radical change to the optimization assumptions for structure layout. Consequently, it is possible to do very tight memory packing without the severe performance penalty traditionally implied.
What constitutes "optimal" structure packing is architecture dependent. The original C structure rules were designed in part to allow the structures to be portable above all else. If you design highly optimized structures for a Haswell processor, code may run much more slowly or create a CPU exception and crash on other architectures, so keep these tradeoffs in mind. The article is discussing basic structure packing which typically has easily predictable behavior almost anywhere C compiles.
Traditionally, C and C++ programs have been compiled by running the compiler on each .c file, and then linking together the results. If each invocation of the compiler could put the fields of a structure in arbitrary order, the different object files would not work together correctly. C structures do not include runtime type information and all offsets are calculated during the compile phase. The same issues come up with libraries. We need a stable application binary interface, or ABI.
Even if the ABI problem was solved, there are advantages to letting the programmer determine the order of fields in a structure. If you know that different threads are going to be using different parts of a structure, you will want to arrange things (or insert padding) so that the different threads are using different cache lines. This avoids so-called "false-sharing."
That just requires that your packing algorithm be deterministic and there's no reason for it not to be.
I suppose it would fail in cases where someone defines a 2 element struct in one file that's a subset of a 3 element struct in another file, and then casts the 3 element into the 2 element.
struct {
char a;
char b;
char c;
char *p;
char d;
}
A valgrind error that points at "0 bytes within an area of memory..." would signal an error originating somewhere in the struct, but who knows whether it's p or a.its more complicated than just keeping the size down though - you might want things to start on 64 or 128 or 256-bit boundaries as well - e.g. if your class contains aligned vector members and is itself aligned.
When I first learned to program in the 80s, this was known as "Fortran order" (as opposed to Pascal or C order), and in the later nineties, I think that "column major" and "row major" became popular, and they still are.
This goes back to sometimes in the 60's, with APL and Fortran doing column major on purpose, BASIC by accident, and most of the rest doing Row major.
It was only a wart because they didn't support compound types at all (and in some cases they did support compound types but people were not taught them when moving to a better language and kept their old techniques). It is compounded by the fact most scripting languages are untyped, so structure packing (the main justification for using arrays like that in more modern languages (for general memory use, stack size, or cache-hit optimisations)) isn't nearly as relevant.
Basically if you see parallel arrays used without a comment stating that it is done for packing reasons or similar, it is there either because the language does not support compound structures well or because the programmer knew no better. In a language where structure packing can be useful, it is a perfectly valid optimisation (though for small data not in tight loops, it may be an optimisation too far).
You are not an advanced C programmer until you have grasped it. You are not a master of C until you could have written this document yourself and can criticize it intelligently
In other words, a "hacker" is someone just like ESR. More blowhardery. I for one don't claim to be a master...
i.e., 'a hacker is someone who looks like me'.
That's longer than I was expecting! I think 2014 is going to be a good year!
Is he? I'm not trying to be insulting, but I honestly can't think of anything that he's done that I might be impressed by.
So yes, chips that can only do aligned memory access do tend to be older.
Listen, I know that there are people who worked into retirement without ever seeing anything other than x86 but a) this shows how old x86 is and b) does not give them expertise over different ISAs.
MIPS is still in the top 4 or so CPU architectures by volume, with x86, PPC, and ARM, with ARM as by far the largest (forecast about 3 billion cores licensed last year).
At least a few hundred million MIPS cores are shipped every year. Depending on what you think embedded x86 volume is, it may be ahead of x86. Of course by revenue x86 still beats everyone.
It's a modern ISA, implemented by modern microarchitectures.
The struct reorg and matrix reorg optimizations (command-line options -fipa-struct-reorg and -fipa-matrix-reorg) have been removed. They did not always work correctly, nor did they work with link-time optimization (LTO), hence were only applicable to programs consisting of a single translation unit.
That's a guess though, no numbers. :)
* http://en.wikipedia.org/wiki/CPU_cache#Cache_entries
* http://stackoverflow.com/questions/14707803/line-size-of-l1-...
struct TCP_Packet {
uint16_t source_port;
uint16_t dest_port;
uint32_t seq_no;
uint16_t flags;
uint16_t window_size;
uint16_t checksum;
unit16_t urgent;
...
} __attribute__ ((packed));> The simplest way to eliminate slop is to reorder the structure members by decreasing alignment. That is: make all the pointer-aligned subfields come first, because on a 64-bit machine they will be 8 bytes. Then the 4-byte ints; then the 2-byte shorts; then the character fields.
I wrote here [1] about using it in a KDE program (KStars) to cut 10% off the memory usage. In particular you can also use this tool to see some of the many bad effects of deeply nested classes: your class may be 8-byte aligned, so a 'char' at the end can take up eight bytes with padding, and it's not possible (AFAIK) to rearrange fields up and down inheritance heirarchies [2].
[1]: http://www.hdevalence.ca/blog/2013-12-22-better-living-throu...
[2]: C++ is not my favorite programming language.
#pragma pack(1)
MSVC
http://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas....
Clang has this, too.
struct SomeCamelCaseNonsenseStructure {
uint8_t flag;
uint32_t pointer;
uint8_t another_flag;
uint32_t another_pointer;
...
}
I feel like flinching every time I read it.small remark: this will cover dates to 2050
that's a bit of a gamble, not sure I would have done that myself. It's probably ok but you never know in 40 years CVS and your code is still in use somewhere and you'll cause some people headaches :]
pub struct stat {
st_dev: dev_t,
__pad1: c_short,
st_ino: ino_t,
st_mode: mode_t,
st_nlink: nlink_t,
st_uid: uid_t,
st_gid: gid_t,
st_rdev: dev_t,
__pad2: c_short,
st_size: off_t,
Note the __pad elements.[1] https://github.com/mozilla/rust/blob/master/src/libstd/libc....
No, a compiler can't do this. You have to assume that the first member of a struct will be machine word aligned. I'm sure there are many reasons, but the one I can think of now is that structs can be dynamically allocated. That means it has to be possible to take the return value of malloc() and assign it to a pointer, and there is no way to get malloc() to return a memory block with that wired alignment (starting on the last byte of a machine word).
Well that's disappointing. Is there any [nonstandard] way to get a compiler to take advantage of that space?
For the rest I blindly trust the compiler to choose optimal boundaries and alignments.
http://jheriko-rtw.blogspot.co.uk/2011/02/know-your-cc-struc...
I seem to remember it being mentioned in Bruce Eckel's excellent "Thinking in C++".
That said, I'm kinda curious how much this affects Objective C objects.