XOR 运算的 4 字节字对齐

发布于 2024-08-15 15:58:28 字数 235 浏览 4 评论 0原文

在字边界上进行按位运算有什么优势吗?这样做有任何 CPU 或内存优化吗?

实际问题: 我正在尝试创建两个结构的异或。假设结构 1 和结构 2 的大小相同,均为 10000 字节。我保留前几百个字节,然后开始 1 和 2 的异或。 假设我从 302 开始。这将一次占用 4 个字节并进行 XOR。两个结构的302、303、304和305将被异或。这个循环将重复到10000。

现在,如果我从304开始,是否会有任何性能改进?

Is there any advantage in doing bitwise operations on word boundaries? Any CPU or memory optimization in doing so?

Actual problem:
I am trying to create XOR of two structure. Lets say structure-1 and structure-2 both of same size 10000 bytes. I leave first few hundreds bytes as it is and then start XOR of 1 and 2.
Lets say I start with 302 to begin with. This will take 4 byte at a time and do XOR. 302, 303, 304 and 305 of both structure will be XORed. This cycle will be repeated till 10000.

Now, If I start from 304, Is there any performance improvement expected?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

水中月 2024-08-22 15:58:28

是的,使用正确的对齐方式至少有两个优点:

  1. 便携性。并非所有处理器都支持非对齐数字。为了获得最大的可移植性,您应该只使用完全对齐(即 N 字节整数从 N 的倍数地址开始)的数字
  2. 速度。 AFAIK,即使是支持非对齐数字的处理器,使用对齐数字仍然会更快。

Yes, there are at least two advantages for using proper alignment:

  1. Portability. Not all processor support non-aligned numbers. For maximum portability, you should only use fully aligned (i.e. an N-byte integer starts at an address that is a multiple of N) numbers
  2. Speed. AFAIK, even a processor that supports non-aligned numbers is still faster with aligned numbers.
巾帼英雄 2024-08-22 15:58:28

过早的优化是万恶之源

只需以简单的方式进行,然后在分析器告诉您优化很重要时进行优化。

是的,如果你正确对齐,你会走得更快。如果您使用 SSE2 向量 XOR 指令,您的速度会更快,在正确对齐的情况下,您将一次执行 16 个字节,并且不会污染缓存。而且您不太可能应该花时间来优化它。

Premature optimization is the root of all evil

Just do it the straightforward way, then optimize it if your profiler tells you it's important.

Yes, you will go faster if you're properly aligned. You'll go even faster if you use the SSE2 vector XOR instructions, where properly aligned you'll do it 16 bytes at a time and not pollute the cache. And it's highly unlikely that optimizing this is where you should be spending your time.

空气里的味道 2024-08-22 15:58:28

某些处理器仅允许在 32 位字边界上进行 4 字节操作(有些处理器仅允许在半字边界上进行)。

在这些处理器上,非对齐访问会导致处理器异常(具体取决于 CPU、操作系统和设置),这将导致进程崩溃或操作系统的大量工作。

在其他处理器(例如 x86)上,您只会因为每次操作必须执行两次读取和写入(加上一点移位)而受到性能影响。

请参阅链接文本以查看 ARM CPU 的问题

Some processors only allow 4-byte operations on 32-bit word boundaries (some allow them only on halfword boundaries).

On these processors non-aligned access causes a processor exception which - depending on CPU, OS and settings - will cause a process crash or just a lot of work for the OS.

On other processors (e.g. x86) you will just get the performance hit of having to do two reads and writes (plus a bit of shifting) per operation.

See link text to see problems with ARM CPUs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文