网上有个对比java和python运行效率的文章,闲的无聊,就把代码用java5和python2.6测试了一下,同样的代码,真是不测不知道一测吓一跳.我没测试完,我觉得测试这些意义不大,毕竟一个系统的运行效率高低和好多方面有关系,不只是简单的几行代码可以测试出来的.所以该测试没任何意义,只是以前有这个文章,我就测试一下,毕竟自己动手出来的结果才更有说服力.测试说明jdk运行效率确实提高了很多.提醒一下,不用要netbeans.eclipse之类的和IDLE对比,要用标准的concle再cmd下运行,如果用IDE的话,测试OUTPUT就不准了,因为java的IDE的输入都有缓存,速度更快.而IDLE却比标准的concle输出要慢的多.
我就测试前三项.这是原来的文章里的.
Test | Java | Python | Comparison |
Standard Output | 138.85 | 30.58 | Python 4.5X Faster than Java |
Hashtable | 17.0 | 8.22 | Python 2X Faster than Java |
I/O | 56.72 | 47.36 | Python 1.2X Faster than Java |
下面是我用jdk5和python2.6测试的
Test | Java | Python | Comparison |
Standard Output | 36.172 | 61.123 | Python 4.5X Faster than Java |
Hashtable | 17.750 | 30.2069186659 | Python 2X Faster than Java |
I/O | 0.390 | 1.41565481607 | Python 1.2X Faster than Java |
代码:
为了能更明显区分,hashtable我用了10000*10000的本来的文章里是1000*1000的,java5和python2.6太快了差别不明显
hashtable如果用1.5之前的不指定类型速度要稍微慢一些,
ConsoleTest | |
Python | Java |
for x in xrange(1000000):
print x
| public class ConsoleTest {
public static void main(String[] args) {
for (int i = 0; i < 1000000; i++) {
System.out.println(i);
}
}
}
|
Hashtest | |
Python | Java |
for i in xrange(10000): x={} for j in xrange(10000): x[j]=i x[j]
| import java.util.Hashtable;
public class HashTest { public static void main(String[] args) { for (int i = 0; i < 10000; i++) { Hashtable x = new Hashtable(); for (int j = 0; j < 10000; j++) { x.put(new Integer(i), new Integer(j)); x.get(new Integer(i)); } } } } |
IOTest | |
Python | Java |
f=open('scratch','wb') for i in xrange(1000000): f.write(str(i)) f.close()
| import java.io.*;
public class IOTest { public static void main(String[] args) { try { File f = new File("scratch"); PrintWriter ps = new PrintWriter(new OutputStreamWriter (new FileOutputStream(f))); for (int i = 0; i < 1000000; i++) { ps.print(String.valueOf(i)); } ps.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } } |