golang java python这几种编程语言做计算密集型任务的性能比较
运行环境
笔记本电脑
cpu:intel i5-3230M@2.6G
windows7 64
golang
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
r := RandInt(10, 13) //产生范围内随机数,防止编译器优化
fmt.Println(r, time.Now().UnixNano())
t := time.Now().UnixNano()
sum := 0
for i := 0; i <= 40000+r; i++ {
for j := 0; j <= 40000; j++ {
sum = sum + i*j
}
}
i := float64(time.Now().UnixNano()-t) / (1000000 * 1000)
fmt.Println(sum)
fmt.Println(i)
}
func RandInt(min, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max-min) + min
}
运行结果
go version
go version go1.9.4 windows/amd64
$ gohello.exe
11 1522927426457018900
640384062001320000
1.0776608
python3.5.2
import time
import random
sum =0
r =random.randint(10,13)
print(r)
t = time.time()
for i in range(40000+r):
for j in range(40000):
sum += i*j
print(sum)
print(time.time()-t)
运行结果
$ python performance_test.py
12
640096001999880000
379.8369143009186
java
import java.util.Random;
public class performance_test{
public static void main(String args[]){
Random rd = new Random();
int r = rd.nextInt(3)+10;
System.out.println(r);
long t1 = System.currentTimeMillis();
long sum =0;
for (int i =0;i<=40000+r;i++){
for (int j=0; j<=40000;j++){
sum += i*j;
}
}
System.out.println(sum);
float a =(float)(System.currentTimeMillis()-t1)/1000;
System.out.println("间隔时间:"+a + "秒");
}
}
java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
javac -d . -encoding utf-8 performance_test.java
java performance_test
11
640384062001320000
间隔时间:0.994秒
结论:
python不出意料不适合做性能密集型的任务
而java的性能出人意料的好,golang的表现和java是同一层次的。
go vs. java
go和java的区别主要在于内存消耗量
go的内存消耗量小 所以在高并发的时候go的优势不仅仅在于程序写法比较简洁(毕竟在程序语言层面就支持协程),而且在于内存优势。
参考下面的benchmark
https://benchmarksgame.alioth.debian.org/u64q/go.html
网友评论