因工作需要,学过几门编程语言,有些时候需要关注程序的运行速度问题,所以特意测试了几门语言的性能。
测试电脑的配置:
CPU: i3-2120 @3.3GHz
RAM: 16GB
OS: Win7 64bit sp1
测试程序:
测试的程序包含循环,函数调用,逻辑比较,数学运算,字符串处理等
1, Java
Java版本:
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)
Java程序:
public class Main {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
for(int i=0; i<10000000; i++){
aaa((float)i);
}
long t2 = System.currentTimeMillis();
System.out.println("java time: " + String.valueOf(t2 - t1) + "ms");
}
static void aaa(float i) {
float a = i + 1;
float b = 2.3f;
String s = "abcdefkkbghisdfdfdsfds";
if(a > b){
++a;
}else{
b = b + 1;
}
if(a == b){
b = b + 1;
}
float c = (float)(a * b + a / b - Math.pow(a, 2));
String d = s.substring(0, s.indexOf("kkb")) + String.valueOf(c);
}
}
javac Main.java
java Main
java time: 1793ms
2, JavaScript
Node版本:
v6.2.0
JavaScript程序:
var t1 = (new Date()).getTime();
for(var i=0; i<10000000; i++){
aaa(i);
}
var t2 = (new Date()).getTime();
console.log("nodejs time:" + (t2 - t1) + "ms");
function aaa(i){
var a = i + 1;
var b = 2.3;
var s = "abcdefkkbghisdfdfdsfds";
if(a > b){
++a;
}else{
b = b + 1;
}
if(a == b){
b = b + 1;
}
var c = a * b + a / b - Math.pow(a, 2);
var d = s.substring(0, s.indexOf("kkb")) + c.toString();
}
node a.js
nodejs time:5474ms
3, Lua
Lua版本:
lua有两个,一个是lua5.2,一个是luajit 2.1.0-beta2
lua程序:
function aaa(i)
a = i + 1
b = 2.3
s = "abcdefkkbghisdfdfdsfds"
if(a > b) then
a = a+1
else
b = b + 1
end
if(a == b) then
b = b + 1
end
c = a * b + a / b - math.pow(a, 2)
d = string.sub(s, 0, string.find(s, "kkb")) .. tostring(c)
end
t1 = os.clock()
for i=0, 10000000, 1 do
aaa(i)
end
t2 = os.clock()
print("lua time: " .. (t2 - t1) * 1000 .. "ms")
luajit a.lua
lua time: 2531ms
lua52 a.lua
lua time: 28447ms
4, Python
Python版本:
Python 2.7.10
Python程序:
import sys, time, math
def aaa(i):
a = i + 1
b = 2.3
s = "abcdefkkbghisdfdfdsfds"
if a > b:
a = a + 1
else:
b = b + 1
if a == b:
b = b + 1
c = a * b +a / b - math.pow(a, 2)
d = s[0: s.find("kkb")] + str(c)
t = time.time()
for i in xrange(0, 10000000):
aaa(i)
print 'Python time: %.02f' % (time.time() - t)
python a.py
Python time: 24.35s
5, GameMonkey
GameMonkey版本:
GameMonkey v1.29.4
GameMonkey程序:
global aaa = function(i) {
a = i + 1;
b = 2.3;
s = "abcdefkkbghisdfdfdsfds";
if(a > b) {
a = a + 1;
} else {
b = b + 1;
}
if(a == b) {
b = b + 1;
}
c = a * b + a / b - power(a, 2);
d = s.Mid(0, s.Find("kkb")) + c.String();
};
TICK();
for(i=0; i<10000000; i=i+1) {
aaa(i);
}
print("GameMonkey time: ", TICK());
gme a.gm
GameMonkey time: 25.25s
6, PHP
PHP版本:
PHP7
PHP程序:
$b){
++$a;
}else{
$b = $b + 1;
}
if($a == $b){
$b = $b + 1;
}
$c = $a * $b + $a / $b - pow($a, 2);
$d = substr($s, 0, strpos($s, 'kkb')) . strval($c);
}
?>
php time: 10000ms 左右
7, 之后有其他语言的再补上
结论:
Java的速度快,JavaScritp跟随其后,PHP有所进步,其他的脚本语言差不多,值得一提的是Luajit 比 JS 的快。