运行速度.png

c,go,python,pypy,codon程序加法速度对比,各编程语言分别从1累加到10亿,并且都是在同一台Ubuntu系统上运行的。

# demo1.py和demo1-pypy.py
import time
t = time.time()
a = 0
for i in range(10**9+1):
  a = a + i
print("python累加结果:", a)
print("运行时间:", time.time() - t, "s")
// demo1.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
    
int main()
{
  // 此处一定要指定long数据类型,否则会有限制,c累加结果: 4051657984 
  long i, a = 0;
  clock_t start_time, end_time;
  double duration_time;
  start_time = clock();
  // pow(10, 9)
  for (i = 0; i <= 1000000000; i++)
  {
      a = a + i;
  }
  end_time = clock();
  printf("c累加结果: %ld \n", a);
  printf("运行时间: %lf s\n", ((double)(end_time - start_time) / CLOCKS_PER_SEC));
  return 0;
}
// demo1.go
package main

import (
  "fmt"
  "strconv"
  "time"
)

func main() {
  var i, a uint64
  var start_timestamp = time.Now().UnixNano() //单位纳秒 //获取当前时间戳,单位纳秒
  for i = 0; i <= 1000000000; i++ {
      a += i
  }
  var end_timestamp = time.Now().UnixNano()
  fmt.Println("go累加结果", a)
  var value, _ = strconv.ParseFloat(fmt.Sprintf("%f", float64(end_timestamp - start_timestamp)/1000000000), 64)
  fmt.Println("运行时间:", value, "s")
}

以下内容是各个运行结果:

python直接运行:

[root@sheng-vc pypy_c_go]# python3 demo1.py
python累加结果: 500000000500000000
运行时间: 163.52063751220703 s

pypy直接运行:

[root@sheng-vc pypy_c_go]# pypy3.9 demo1_pypy.py
pypy累加结果: 500000000500000000
运行时间: 2.0093536376953125 s

codon直接运行:

[root@sheng-vc pypy_c_go]# codon run demo1.py
python累加结果: 500000000500000000
运行时间: 1.9895 s

codon编译输出可执行文件,运行:

[root@sheng-vc pypy_c_go]# codon build -o demo1_codon demo1.py
[root@sheng-vc pypy_c_go]# ./demo1_codon
python累加结果: 500000000500000000
运行时间: 2.1441 s

codon利用优化器编译输出可执行文件,运行。神速,比最快的go快4个数量级

[root@sheng-vc pypy_c_go]# codon build -o demo1_codon_optimizations -release demo1.py
[root@sheng-vc pypy_c_go]# ./demo1_codon_optimizations
python累加结果: 500000000500000000
运行时间: 7.86781e-05 s
0.000078 s

0.000078 s

c编译输出可执行文件,运行:

[root@sheng-vc pypy_c_go]# gcc -o demo1_c demo1.c
[root@sheng-vc pypy_c_go]# ./demo1_c
c累加结果: 500000000500000000
运行时间: 3.400000 s

go编译输出可执行文件,运行:

[root@sheng-vc pypy_c_go]# go build -o demo1_go demo1.go
[root@sheng-vc pypy_c_go]# ./demo1_go
go累加结果 500000000500000000
运行时间: 0.4734 s
编程语言cgopythonpypycodon
最快运行速度(s)3.40000.4734163.52062.00930.000078 s
综上所述,运行速度最快的是codon编程,但是可惜很多python模块还不支持,windows平台也不适配,无法做到通用性,比较通用的快速的还是go大神啊!

热血的青春
1 声望0 粉丝

研究自动化,智能化技术