Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c++ Subject: Re: Performance of unaligned memory-accesses Date: Wed, 07 Aug 2019 15:51:05 -0700 Organization: None to speak of Lines: 42 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="c2e3c649afb59b0d1215e9c099fa96fa"; logging-data="24270"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18GYGKo9RT+aaDFrYgtQE2P" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1://KnmMOOvIGfKp4HnMuQN0EGM+s= sha1:9CoLQCfagsjefJiGJmWyjUoSPHs= Xref: csiph.com comp.lang.c++:67411 David Brown writes: > On 07/08/2019 14:47, Bonita Montero wrote: >>> What's the point of the exercise, in a C++ context? Unaligned access >>> in portable code is always the result of a programming error. >> >> Pure theory. All platforms support unaligned access either directly >> through the CPU or through trapping by the operating-system (very slow). > > No, they don't. Some cpus support direct unaligned accesses. For > others, various things could happen. On big OS's, you are likely to get > a trap or exception causing the OS to kill your program with a fault - I > can't imagine why an OS would bother simulating the unaligned access. > On embedded systems, unaligned access may lead to a bus fault of some > sort, halting the system or causing a restart. And on some systems that > I have used, unaligned access will silently give you muddled reads and > corrupting writes. Agreed. > Unaligned access is always an error. Use code with shifts and masks, if > you need it, or use memcpy. If your compiler isn't good enough to give > you efficient enough code for your needs, get a better compiler. I suppose that depends on what you mean by "unaligned". For example, as I understand it x86 and x86_64 support accessing words at odd addresses in hardware, using the same CPU instructions as an aligned access but executing more slowly. If you want to extract a 32-bit value from an odd address, and you know you're running on an x86 or x86_64 and you're not concerned with portability, you might as well use a word move instruction in assembly or a simple assignment in C++. You *could* break it down into byte moves, but the resulting code would be slower. For some CPUs, aligned access gives you better performance, but unaligned access still works. For others, unaligned access just goes kablooie. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Will write code for food. void Void(void) { Void(); } /* The recursive call of the void */