Java和PyPy运行同一段代码,对比结果.
Java代码:
package javatest;
import java.text.DecimalFormat;
import java.util.Date;
public class speedTest
{
public static void main(String[] args)
{
int i = 0;
int max = 2000000;
Date start = new Date();
while (i++ < max)
{
transform();
}
Date end = new Date();
long diff = end.getTime() - start.getTime();
StringBuffer maxToshow=new StringBuffer();
maxToshow.append(max);
int count=0;
for(int a=1;a<String.valueOf(max).length();a++)
{
if(a%3==0)
{
count++;
maxToshow.insert(String.valueOf(max).length()-count*3, ",");
}
}
//String s = String.format("it takes %f seconds to run %s loops",
// diff / 1000.00, new DecimalFormat(",###").format(max));
String s = String.format("it takes %f seconds to run %s loops",
diff / 1000.00, maxToshow.toString());
System.out.println(s);
}
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
import numFormatter
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:
1==1#sys.stdout.write(s)
def formatNumber(number):
numStr='%d'%number
formatStr=''
numStr=numStr[::-1]
i=0
while i<len(numStr):
formatStr+=numStr[i]
i+=1
if i%3==0:
formatStr+=','
formatStr=formatStr.strip(',')
formatStr=formatStr[::-1]
print formatStr
starttime = datetime.datetime.now()
loops=200000;
for i in range(loops):
transform()
#sys.stdout.write('\n')
endtime = datetime.datetime.now()
print 'it takes %s seconds to run %s loops'%((endtime - starttime).seconds,formatNumber(loops))
Java分别运行两百万次、两千万次、两亿次耗时结果:
![](https://i-blog.csdnimg.cn/blog_migrate/017f23464570b6a184bdceb9de967375.png)
![](https://i-blog.csdnimg.cn/blog_migrate/75269ea38f120094cce542d91dd04b5d.png)
![](https://i-blog.csdnimg.cn/blog_migrate/34bcdfad8545d26cfb65345db5a2d6f8.png)
PyPy运行上述代码,两百万次、两千万次、两亿次的耗时结果:
![](https://i-blog.csdnimg.cn/blog_migrate/9e29682346914fd70b269d4d2fa2e65c.png)
PyPy和Python解释器运行结果对比:
![](https://i-blog.csdnimg.cn/blog_migrate/760e9dd7a53f71a77b8ae3e04179bc7a.png)
依据结果粗略估计,Java效率是PyPy的2.3倍,PyPy是Python的88.5倍