Apple Darwin User Manual Page 57

  • Download
  • Add to my manuals
  • Print
  • Page
    / 68
  • Table of contents
  • BOOKMARKS
  • Rated. / 5. Based on customer reviews
Page view 56
Avoiding Unaligned Accesses
If you create data structures with packed alignment, you may see a performance regression caused by unaligned
access penalties. For example:
#pragma pack(1)
typedef struct
{
long a;
int b;
int b1;
int b2;
long double c;
} myStruct;
#pragma options align=reset
Ideally, the variable c should be aligned on a 16-byte boundary. In a 32-bit environment, it ends up aligned
correctly because the variable a is 4 bytes long. In a 64-bit environment, this variable ends up offset by 4 bytes
from its ideal position because the variable a is 8 bytes long.
While a single unaligned access penalty is relatively small, the cumulative effects can be significant. Given a
loop that assigns the value zero (0) repeatedly to variables a, b, and c, you can improve performance of the
loop by more than 20% by simply moving the variable b2 after the variable c. Of course, this wrecks performance
in the 32-bit version because variable c is then unaligned.
The best solution is to not use packing pragmas except when working with data structures that mandate it
(structures that represent hardware registers or are intended to be written to a file, sent across a network
connection, shared across address space boundaries, and so on) and let the compiler use natural alignment
for all data structures that you work with on a regular basis in your software.
For maximum efficiency, you should also reorder this structure to place the variable c first, followed by the
variable a, followed by the remaining variables (in order from largest alignment size to smallest). This achieves
optimal packing efficiency while avoiding alignment penalties regardless of CPU architecture and often obviates
the need for packing pragmas.
Performance Optimization
Avoiding Unaligned Accesses
2012-12-13 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
57
Page view 56
1 2 ... 52 53 54 55 56 57 58 59 60 61 62 ... 67 68

Comments to this Manuals

No comments