Java和Python运行速度对比

Java和Python运行速度对比:同一个函数运行一百万次,Java耗时0.577秒,Python耗时78秒--135倍的差距。

版本:Java 8,Python 2.7.10

Java测试代码:

import java.util.Date;

public class test
{
 public static void main(String[] args)
 {
  Date start = new Date();
  for (int i = 0; i < 1000000;
i++)
  {
   transform();

}
  Date end = new Date();
  long diff = end.getTime() -
start.getTime();
  System.out.println("it takes
"+diff/1000.00+" seconds");
 }

public static void transform()
 {
  String str = "Pcybgle rfgq
rsrmpgyj fyq npmzyzjw pcgldmpacb wmsp glrcpcqr gl sqgle Nwrfml -
wms qfmsjb zc cyecp rm ynnjw Nwrfml rm qmjtgle wmsp pcyj-umpjb
npmzjckq. Ufcpc qfmsjb wms em rm jcypl kmpc?";
  for (int i = 0; i <
str.length(); i++)
  {
   char c =
str.charAt(i);
   if (c >=
'a' && c <= 'z')
   {
    c
+= 2;
    if
(c > 'z')
    {

c
-= 26;
    }

System.out.print(c);

}
   else if (c
>= 'A' && c <= 'Z')
   {
    c
+= 2;
    if
(c > 'Z')
    {

c
-= 26;
    }

System.out.print(c);

}
   else
    System.out.print(c);

}
 }
}

Python测试代码:

import sys,datetime

def transform():
   
str='''Pcybgle rfgq rsrmpgyj fyq npmzyzjw pcgldmpacb wmsp glrcpcqr
gl sqgle Nwrfml - wms qfmsjb zc cyecp rm ynnjw Nwrfml rm qmjtgle
wmsp pcyj-umpjb npmzjckq. Ufcpc qfmsjb wms em rm jcypl
kmpc?'''
    for s in
str:
       
if ord(s)>=ord('a') and ord(s)<=ord('z'):
           
new=ord(s)+2
           
if new>ord('z'):
               
new-=26
           
sys.stdout.write(chr(new))
       
elif ord(s)>=ord('A') and ord(s)<=ord('Z'):
           
new=ord(s)+2
           
if new>ord('Z'):
               
new-=26
           
sys.stdout.write(chr(new))
       
else:
           
sys.stdout.write(s)

starttime = datetime.datetime.now()
for i in range(1000000):
   
transform()
   
endtime = datetime.datetime.now()

print 'it takes %s seconds'%(endtime - starttime).seconds

上一篇:MinGW GCC 7.1.0 2017年6月份出炉啦


下一篇:tornado之WebSocket