Re: Why is Java so slow????
In article <Zfo0j.9233$pg.4536@newsfe6-win.ntli.net>,
Mark Thornton <mark.p.thornton@ntl-spam-world.com> wrote:
The main reason your Java code was so slow relative to C is that you had
not taken account of the special characteristics of System.out.
I tried running the code Lew posted, redirected, with the following
results:
JAVA:
$ time java -server -classpath . TimePrin > out.txt
real 0m31.306s
user 0m15.430s
sys 0m14.705s
$ time java -server -classpath . TimePrin > /dev/null
real 0m20.474s
user 0m14.085s
sys 0m6.233s
C:
$ time ./a.out > out.txt
real 0m4.680s
user 0m1.302s
sys 0m0.650s
$ time ./a.out > /dev/null
real 0m1.366s
user 0m1.248s
sys 0m0.010s
It is a
line buffered PrintStream. To avoid this characteristic try writing to a
file instead or creating a new stream on FileDescriptor.out like this:
PrintStream out = new PrintStream(new BufferedOutputStream(new
FileOuputStream(FileDescriptor.out)));
Trivially rewriting it to use a wrapped FileOutputStream yields:
kandidat:~/tmp bcd$ time java -server -classpath . TimePrin
Elapsed: 5.223 secs.
real 0m5.410s
user 0m4.679s
sys 0m0.521s
This value of 5.41s is reasonably close to C's 4.68s, but the Java
program needed to be written specifically to output to file whileas C
achieved this performance by simple redirection.
The code used is:
import java.util.Date;
import java.io.*;
public class TimePrin
{
private static final int LIM = 5000000;
public static void main( String [] args)
throws Exception
{
int lim;
if ( args.length < 1 )
{
lim = LIM;
}
else
{
try
{
lim = Integer.parseInt( args [0] );
}
catch ( NumberFormatException ex )
{
lim = LIM;
}
}
long start = new Date().getTime();
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("out.txt")));
for ( int i=0; i < lim; i++)
{
out.print( "This is line " + i +"\n" );
}
out.close();
long end = new Date().getTime();
double elapsed = (end - start) / 1000.0;
System.out.println( "Elapsed: "+ elapsed +" secs." );
}
}
Cheers,
Bent D
--
Bent Dalager - bcd@pvv.org - http://www.pvv.org/~bcd
powered by emacs