6

Java Go python 运行速度对比

 1 year ago
source link: https://studygolang.com/articles/25933?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java Go python 运行速度对比

System: CentOS Linux release 7.7.1908
Memory: 2G
CPU: 1 * Intel(R) Xeon(R) CPU E5-2682 v4 @ 2.50GHz
Java: 1.8.0_131
Python: Python 3.7.3
Golang: go1.13.3 linux/amd64

选用常用的冒泡排序分别使用三种语言进行1亿次排序,然后对比排序的最终时间。

先使用 javac 编译 Speed.java 文件得到 Speed 字节码文件然后使用 time 命令计算程序运行的时间time java Speed

public class Speed {

    public static void main(String[] args) {
        int num = 1000000000;
        long start = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            bubbleSort(1, 2, 3, 4, 5, 6, 7, 8, 9);
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    public static void bubbleSort(int... arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] < arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

}

java Speed 4.62s user 0.05s system 97% cpu 4.776 total

Golang

先编译 Golang 源文件 go build 然后运行编译后的文件 time ./speed

package main

import (
    "fmt"
    "time"
)

func bubbleSort(arr []int) {
    for j := 0; j < len(arr)-1; j++ {
        for k := 0; k < len(arr)-1-j; k++ {
            if arr[k] < arr[k+1] {
                temp := arr[k]
                arr[k] = arr[k+1]
                arr[k+1] = temp
            }
        }
    }
}

func main() {
    const NUM int = 1000000000
    var arr []int
    start := time.Now().UnixNano()
    for i := 0; i < NUM; i++ {
        arr = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
        bubbleSort(arr)
    }
    fmt.Println((time.Now().UnixNano() - start) / 1e6)
}

./speed 9.23s user 0.09s system 51% cpu 18.143 total

Python

直接使用 time 命令计算程序运行的时间time Python speed.py

# coding:utf-8
import time


def bubble_sort(arr):
    for i in range(len(arr)):
        for j in range(len(arr) - 1 - i):
            if arr[j] < arr[j + 1]:
                temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp


if __name__ == '__main__':
    NUM = 100000000
    data = []
    s = time.clock()
    for k in range(NUM):
        data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        bubble_sort(data)
    print(int((time.clock() - s) * 1000))

python speed.py 1722.12s user 2.75s system 98% cpu 29:19.88 total

Python Golang Java
1722.12s 9.23s 4.62s

测试结果有点出乎意料,Python 的速度也太慢了吧。不过 Java 比 Golang 还要快一倍左右更出乎意料,也可能测试的纬度太过局限,没有网络io和磁盘io等其他方面的对比。其实编程语言的速度并非是衡量一种语言优劣的唯一标准,每种语言都有自己擅长的领域,不过程序的优劣和coder也有很大关系。


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK