我正在从事一个对性能至关重要的项目,其中每个时钟周期在我最重要的内部循环中都很重要。我正在考虑重组代码以隐藏指令延迟,但我想知道现代 CPU 的乱序执行硬件在多大程度上已经为我做到了这一点。考虑以下(简单的、假设的)示例:
// Increment three counters. These instructions should all execute in
// parallel with latency of one cycle. Assume the previous register values
// have been computed a long time ago and are ready to use by the time
// these are decoded.
add RAX, 1;
add RBX, 2;
add RCX, 3;
// Multiply takes at least three cycles. Again, assume both inputs are
// ready by the time we get here.
imul RDX, RDI;
// Use the result of the imul immediately in a long dependency chain.
mov RDX, [RDX];
cmp RDX, 1;
jae LBlahBlahBlah;
我的问题是以下哪一项适用:
现代主流的乱序硬件将对
imul
三个add
指令之前的指令重新排序,即使add
指令以编程方式出现在指令之前,imul
并且在它们被解码时它们的所有输入依赖项都可用。具有imul
比add
指令更长的延迟,并且在依赖链中立即使用,因此这是最佳的。乱序执行仅在由于缺少输入依赖项而在解码时无法以编程方式执行的较早指令时发生。不能指望硬件“向前看”来动态优化这样的事情。