问题描述
我正在运行一些测试来比较 C 和 Java 并遇到了一些有趣的事情。在 main 调用的函数中而不是在 main 本身中运行优化级别 1 (-O1) 的完全相同的基准代码,导致性能大约翻倍。我正在打印 test_t 的大小,以毫无疑问地验证代码是否正在编译为 x64。
我将可执行文件发送给运行 i7-7700HQ 的朋友并得到了类似的结果。我正在运行 i7-6700。
这是较慢的代码:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
int main() {
printf("Size = %I64u\n",sizeof(size_t));
int start = clock();
for(int64_t i = 0; i < 10000000000L; i++) {
}
printf("%ld\n",clock() - start);
return 0;
}
而且速度更快:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
void test() {
printf("Size = %I64u\n",clock() - start);
}
int main() {
test();
return 0;
}
我还将提供汇编代码供您深入研究。我不知道组装。 较慢:
.file "dummy.c"
.text
.def __main; .scl 2; .type 32; .endef
.section .rdata,"dr"
.LC0:
.ascii "Size = %I64u\12\0"
.LC1:
.ascii "%ld\12\0"
.text
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
pushq %rbx
.seh_pushreg %rbx
subq $32,%rsp
.seh_stackalloc 32
.seh_endprologue
call __main
movl $8,%edx
leaq .LC0(%rip),%rcx
call printf
call clock
movl %eax,%ebx
movabsq $10000000000,%rax
.L2:
subq $1,%rax
jne .L2
call clock
subl %ebx,%eax
movl %eax,%edx
leaq .LC1(%rip),%rcx
call printf
movl $0,%eax
addq $32,%rsp
popq %rbx
ret
.seh_endproc
.ident "GCC: (x86_64-posix-seh-rev0,Built by MinGW-W64 project) 8.1.0"
.def printf; .scl 2; .type 32; .endef
.def clock; .scl 2; .type 32; .endef
更快:
.file "dummy.c"
.text
.section .rdata,"dr"
.LC0:
.ascii "Size = %I64u\12\0"
.LC1:
.ascii "%ld\12\0"
.text
.globl test
.def test; .scl 2; .type 32; .endef
.seh_proc test
test:
pushq %rbx
.seh_pushreg %rbx
subq $32,%rsp
.seh_stackalloc 32
.seh_endprologue
movl $8,%rcx
call printf
nop
addq $32,%rsp
popq %rbx
ret
.seh_endproc
.def __main; .scl 2; .type 32; .endef
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
subq $40,%rsp
.seh_stackalloc 40
.seh_endprologue
call __main
call test
movl $0,%eax
addq $40,%rsp
ret
.seh_endproc
.ident "GCC: (x86_64-posix-seh-rev0,Built by MinGW-W64 project) 8.1.0"
.def printf; .scl 2; .type 32; .endef
.def clock; .scl 2; .type 32; .endef
这是我的编译批处理脚本:
@echo off
set /p file= File to compile:
del compiled.exe
gcc -Wall -Wextra -std=c17 -O1 -o compiled.exe %file%.c
compiled.exe
PAUSE
以及编译为汇编:
@echo off
set /p file= File to compile:
del %file%.s
gcc -S -Wall -Wextra -std=c17 -O1 %file%.c
PAUSE
解决方法
慢版:
请注意,sub rax,1 \ jne
对正好穿过 ..80
的边界(这是一个 32 字节的边界)。这是 Intels document regarding this issue 中提到的情况之一,如下图所示:
所以这个 op/branch 对 受到 the fix for the JCC erratum 的影响(这会导致它没有被缓存在 µop 缓存中)。我不确定这是否是原因,还有其他因素在起作用,但这是一回事。
在快速版本中,分支不会“触及”一个 32 字节的边界,因此不受影响。
可能还有其他适用的效果。仍然由于跨越 32 字节边界,在缓慢的情况下,循环分布在 µop 缓存中的 2 个块中,即使没有修复 JCC 错误,如果循环无法从循环执行,则可能导致它每次迭代运行 2 个周期流检测器(在某些处理器上被其他勘误的其他修复程序禁用,SKL150)。参见例如关于 loop performance 的答案。
为了解决各种评论说他们无法重现这一点,是的,有多种可能发生的方式:
- 无论哪种影响导致速度变慢,很可能是由于操作/分支对在 32 字节边界上精确放置造成的,这纯属偶然。从源代码编译不太可能重现相同的情况,除非您使用与原始发布者使用的设置相同的编译器。
- 即使使用相同的二进制文件,无论哪个效果负责,奇怪的效果只会发生在特定的处理器上。