这里的答案是确切的时间会有所不同。当我在我的机器上运行这段代码时,它有时会为第一个循环提供 1000,而在其他时候为第二个循环提供 1000。当计时器计时结束时,这只是“运气”。如果您有更准确的计时器,它可能会根据读取计时器所需的时间或类似情况显示差异。
$ ./a.out
k = 1000000
k = 1000000
Simple: 0
Double: 1000
$ ./a.out
k = 1000000
k = 1000000
Simple: 1000
Double: 0
$ ./a.out
k = 1000000
k = 1000000
Simple: 1000
Double: 0
$ ./a.out
k = 1000000
k = 1000000
Simple: 1000
Double: 0
很容易看出两个循环都被优化了:
main:
.LFB1474:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
pushq %rbx
.cfi_def_cfa_offset 24
.cfi_offset 3, -24
subq $8, %rsp
.cfi_def_cfa_offset 32
call _ZNSt6chrono12system_clock3nowEv
movq %rax, %rbx
call _ZNSt6chrono12system_clock3nowEv
movl $.LC0, %esi
**subq %rbx, %rax**
movl $_ZSt4cout, %edi
imulq $1000, %rax, %rbp
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
**movl $1000000, %esi**
movq %rax, %rdi
call _ZNSo9_M_insertImEERSoT_
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
call _ZNSt6chrono12system_clock3nowEv
movq %rax, %rbx
call _ZNSt6chrono12system_clock3nowEv
movl $.LC0, %esi
**subq %rbx, %rax**
movl $_ZSt4cout, %edi
imulq $1000, %rax, %rbx
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
**movl $1000000, %esi**
movq %rax, %rdi
call _ZNSo9_M_insertImEERSoT_
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
movl $.LC1, %esi
movl $_ZSt4cout, %edi
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
movq %rbp, %rsi
movq %rax, %rdi
call _ZNSo9_M_insertIlEERSoT_
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
movl $.LC2, %esi
movl $_ZSt4cout, %edi
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
movq %rbx, %rsi
movq %rax, %rdi
call _ZNSo9_M_insertIlEERSoT_
movq %rax, %rdi
call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
addq $8, %rsp
.cfi_def_cfa_offset 24
xorl %eax, %eax
popq %rbx
.cfi_def_cfa_offset 16
popq %rbp
.cfi_def_cfa_offset 8
ret
您可以清楚地看到 K 的常量作为常量插入到流中,并且“之前”和“之后”的时间被取走,然后减去,中间没有(很多)代码。(“有趣的”位标有** ... **
- 它当然不会在代码中使其变为粗体)