Why is my Java program running 4 times faster via Eclipse than via shell?
When I execute the开发者_JAVA技巧 simple code sample below via Eclipse (version 3.5.2, on Ubuntu 10.04, java version "1.6.0_20" OpenJDK Runtime Environment (IcedTea6 1.9.9) (6b20-1.9.9-0ubuntu1~10.04.2) OpenJDK Server VM (build 19.0-b09, mixed mode)), it takes about 10 seconds. When I execute it from my shell (using the same priority and java version), it takes about 40 seconds.
for (int i = 0; i<1000*1000; i++) {
System.out.println(Math.cos(i));
}
I also tried other programs, varying in runtime and amount of output: Each one was much slower in the shell. This was independent of the order of execution. The minimum percentage difference was 85 seconds in Eclipse vs. 145 seconds in shell for a program with very little output.
What's the reason?
It's because you're timing your terminal. Some terminals are just bog-slow when displaying/scrolling text. And your terminal is line buffered, vs the eclipse console likely have more buffering - leading to your program having to wait for your terminal after every line it prints.
Try redirecting the output of your program to a file or /dev/null, and time it.
On my system this makes a bit difference with your little loop:
$ time java T --snip - 1M lines of output-- real 0m24.746s user 0m2.403s sys 0m1.597s $ time java T >output real 0m5.172s user 0m2.800s sys 0m2.707s
Since by far the most time your program spends in doing output, the overall time of execution is very much depending on the time your system call takes for that. So putting it on the regular console seems to be much slower than the output window in eclipse, but that does not mean, your program itself is executed faster.
Just direct all output into a file and you won't see much difference any more.
Two possibilities come to mind. First, in Eclipse, the Java machinery is already fired up; perhaps running from the shell incurs significant start-up overhead. Try timing just the loop itself (using System.currentTimeMillis()
).
Second, perhaps your configuration is such that Java running from the shell has JIT disabled. That might significantly slow down a program. Check your environment variables for anything that might disable the JIT compiler.
How are you measuring time? By using System.nanoTime()
? (If you are measuring time externally, keep in mind the time to bootstrap the VM).
Try to do the following:
- Modify your main method to do a warm up run first without recording times.
- Then measure the time for several others run using
System.nanoTime()
. - See if there's any significant difference of performance between the averaged time measured from console and Eclipse.
精彩评论