为什么Java的运行比C快在这里? [英] Why Java is running faster than C here?
问题描述
这个问题,
<子>现在唯一可见对于> 10K代表用户
我想出了以下code:
I came up with the following code:
$cat loop.c
int main( int argc, char ** argv )
{
int i = 0;
while( i++ < 2147483647 );
}
$cc -o loop loop.c
$ time ./loop
real 0m11.161s
user 0m10.393s
sys 0m0.012s
$cat Loop.java
class Loop {
public static void main( String [] args ) {
int i = 0;
while( i++ < 2147483647 );
}
}
$javac Loop.java
$time java Loop
real 0m4.578s
user 0m3.980s
sys 0m0.048s
为什么Java版本运行近3倍比C版快?什么,我在这里丢失?
Why does the Java version runs almost 3x faster than the C version? What I'm missing here?
这是在Ubuntu 9.04与运行:
This is run on Ubuntu 9.04 with:
英特尔(R)奔腾(R)M @ 1.73GHz的
Intel(R) Pentium(R) M @ 1.73GHz
32位
修改
这是惊人的。使用在C -O3选项优化循环,并在Java中使用-server不相同。这是优化时代。
This is amazing. Using the -O3 option in C optimize the loop and using -server in Java does the same. This are the "optimized times".
推荐答案
我期待的javac
被默认为优化比你的C编译器的一些更高的水平。当我编译 -O3
这里,C是更快的方式:
I expect javac
is defaulting to some higher level of optimization than your C compiler. When I compile with -O3
here, the C is way faster:
用C -O3
:
real 0m0.003s
user 0m0.000s
sys 0m0.002s
Java程序:
Your java program:
real 0m0.294s
user 0m0.269s
sys 0m0.051s
更多的细节;没有优化的C编译为:
Some more details; without optimization, the C compiles to:
0000000100000f18 pushq %rbp
0000000100000f19 movq %rsp,%rbp
0000000100000f1c movl %edi,0xec(%rbp)
0000000100000f1f movq %rsi,0xe0(%rbp)
0000000100000f23 movl $0x00000000,0xfc(%rbp)
0000000100000f2a incl 0xfc(%rbp)
0000000100000f2d movl $0x80000000,%eax
0000000100000f32 cmpl %eax,0xfc(%rbp)
0000000100000f35 jne 0x00000f2a
0000000100000f37 movl $0x00000000,%eax
0000000100000f3c leave
0000000100000f3d ret
通过优化( -O3
),它看起来像这样:
With optimization (-O3
), it looks like this:
0000000100000f30 pushq %rbp
0000000100000f31 movq %rsp,%rbp
0000000100000f34 xorl %eax,%eax
0000000100000f36 leave
0000000100000f37 ret
正如你所看到的,整个循环已被删除。 的javap -c循环
给了我这个输出为Java字节code:
As you can see, the entire loop has been removed. javap -c Loop
gave me this output for the java bytecode:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: iinc 1, 1
6: ldc #2; //int 2147483647
8: if_icmpge 14
11: goto 2
14: return
}
看来环路编译,我想事情发生在运行时加快了一个。 (正如其他人所提到的,JIT编译器南瓜圈外。)
It appears the loop is compiled in, I guess something happens at runtime to speed that one up. (As others have mentioned, the JIT compiler squashes out the loop.)
这篇关于为什么Java的运行比C快在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!