Java vs. C Simple Performance Test [closed]
im running a simple loop that prints out the iterator (i) for 1.000.000 times in both java and c.
im using netbeans and visual studio respectively.
i dont care about precision but at about 40 seconds:
netbeans (java) has printed about 500.000 numbers while windows (c) has printed about 75.000 numbers
-- why such a big difference?
im using a common intel core2duo(2.0 Ghz) pc with windows7
That seems wrong. Could you provide your code?
My Versions:
C version compiled with gcc -std=c99 -o itr itr.c
with gcc 4.5.1
#include <stdio.h>
int main( int argc, char **argv )
{
for ( int i = 0; i < 1000000; i++ )
{
printf("%d\n", i);
}
}
Java Version compiled as javac Itr.java
with javac 1.6.0_20
and JVM being:
OpenJDK Runtime Environment (IcedTea6 1.9.1) (ArchLinux-6.b20_1.9.1-1-x86_64)
OpenJDK 64-Bit Server VM (build 17.0-b16, mixed mode)
code -
class Itr
{
public static void main( String[] av )
{
for ( int i = 0; i < 1000000; i++ )
{
System.out.println(i);
}
}
}
and the times:
time ./itr
// Snip Output //
real 0m1.964s
user 0m0.330s
sys 0m1.477s
time java Itr
// Snip Output //
real 0m5.245s
user 0m2.337s
sys 0m3.023s
The test system is a Intel Core i5 M520 ( @ 2.4GHz ) running 64 bit ArchLinux.
One way to considerably speed up your example would be:
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000000; i++)
sb.append(i).append("\n");
System.out.println(sb.toString());
}
String concatenation or output (in your case printing to standard output stream) in a loop is bad by design and not the fault of Java, you just generally want to avoid that.
It is much faster if you minimize the calls to output and use a local buffer. Also concatenating Strings is also inefficient - Java has StringBuilder
class for that task.
- Without providing your code and environnement settings, your test have no value.
- Are you sure that the NetBeans console display isn't slown down in C case, or optimized for Java output?
- Are you sure you did run the two projects in optimized mode without debug? C debug versions often generate a lot of debug informations that clearly slow down everything if you're debugging. Anyway, any benchmark should be done with optimization AND no debug mode.
精彩评论