我想我在不使用 Boost 的情况下找到了更好的解决方案:
#pragma GCC push_options
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize ("O2")
void nops() {
int i = 0;
for(; i < 10 ; i++) {
asm volatile("nop");
}
}
#pragma GCC pop_options
int main(void) {
nops();
}
编译:
gcc -c -o test.o -O3 test.c
拆机看看:
objdump -d test.o
test.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <nops>:
0: 90 nop
1: 90 nop
2: 90 nop
3: 90 nop
4: 90 nop
5: 90 nop
6: 90 nop
7: 90 nop
8: 90 nop
9: 90 nop
a: c3 retq
Disassembly of section .text.startup:
0000000000000000 <main>:
0: 31 c0 xor %eax,%eax
2: e8 00 00 00 00 callq 7 <main+0x7>
7: f3 c3 repz retq