Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

code alignment

Status
Not open for further replies.

Geeco

Technical User
Jun 30, 2003
8
FI
Hi,

What does code alignment mean? I know it makes code execution more efficient but howto take it into consideration for example when sorting different data types in struct, if the struct contains char, byte array ([20]), unsigned long int, unsigned short int etc. types?

Thanks 4 help.
 
> howto take it into consideration for example when sorting different data types in struct
As far as sorting is concerned, sorting an array of ints or sorting an array of structures is the same, the only difference is the size of the elements of the array.

Obviously, this gets expensive as the size of each array element grows, so you would want to avoid sorting such arrays directly. My preferred solution is to sort an array of pointers rather than the array itself.

Are you suggesting that something like
Code:
#pragma pack(1)
to reduce the size of each structure would be somehow beneficial? Whilst it may speed up copying by saving a few bytes here and there, its more likely to slow things down since accessing the structure is now more complicated for the compiler.

--
 
Alignment is something your compiler and linker will handle for you. It goes right back to the beginings of the 8086 processor family, and works like this:
Although memory is addressed by byte (every byte has a different address), the processor retrieves it by (at least) word. This was even true of the 8086, I think. If you have word-sized data sitting at an even address, a single word can be retrieved in a single read. If it's at an odd address, the processor needs to retrieve two words, the first to get the low byte of the word it's looking for, the next to get the high byte. This obviously slows things down enormously.
And yes, it's still an issue today. With caches and bits and pieces, the last time I tried this on a pentium, mucking about in assembler, I managed to get a piece of code to double in speed by inserting a nop! It was a question of shunting some data to be in alignment.

But you needn't go overboard about this. Compilers will align data and code as appropriate. In general, maloc-like functions in all languages return sensibly aligned addresses. Some people get worried about aligning to greater than a word (align to paragraph or whatever), but in virtually all applications that's excessive. If you waste memory too much you run a risk of cache misses instead, which are just as bad.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top