By looking at the assembler code using g++ -O2 -fverbose-asm -S -std=c++11 test.cc I see that the compiler computed the result at compile time: .globl main .type main, @function main: .LFB1530: .cfi_startproc pushq %rbx # .cfi_def_cfa_offset 16 .cfi_offset 3, -16 call _ZNSt6chrono3_V212system_clock3nowEv # movabsq $2305843005992468481, %rsi #, movl $_ZSt4cout, %edi #, movq %rax, %rbx #, start call _ZNSo9_M_insertIxEERSoT_ # movq %rax, %rdi # D.35007, call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ # call _ZNSt6chrono3_V212system_clock3nowEv # subq %rbx, %rax # start, D.35008 movl $_ZSt4cout, %edi #, movq %rax, %rsi # D.35008, D.35008 call _ZNSo9_M_insertIlEERSoT_ # movq %rax, %rdi # D.35007, call _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ # xorl %eax, %eax # popq %rbx # .cfi_def_cfa_offset 8 ret .cfi_endproc .LFE1530: .size main, .-main因此,您只需要在编译器中启用优化(或切换到更好的编译器,例如 海湾合作委员会 4.9)So you just need to enable optimizations in your compiler (or switch to a better compiler, like GCC 4.9)顺便说一下,Java 低级优化发生在 JIT 的 JITa href="http://en.wikipedia.org/wiki/JVM" rel="nofollow noreferrer">JVM.我不太了解 JAVA,但我认为我不需要打开它们.我知道在 GCC 上你需要启用优化,这当然是提前(例如使用 -O2)BTW on Java low level optimizations happen in the JIT of the JVM. I don't know JAVA well but I don't think I need to switch them on. I do know that on GCC you need to enable optimizations which of course are ahead of time (e.g. with -O2)PS:我在 21 世纪从未使用过任何 Microsoft 编译器,因此我无法帮助您在其中启用优化.最后,我认为这样的微基准测试并不重要.然后进行基准测试来优化您的实际应用.At last, I dont believe that such microbenchmarks are significant. Benchmark then optimize your real applications. 这篇关于为什么这个简单的 C++ 加法比等效的 Java 慢 6 倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 23:45