对比JAVA、Python、C、Go运行时间,我惊呆了!!!
周末在寝室刷完算法,想放松一下,于是做了一个实验:用现在主流的几种编程语言对0 - (10000000 - 1)求和,结果我惊呆了,话不多说,show me your code!!!
python
import time
sum = 0
start = time.time()
for i in range(10000000):
sum += i
end = time.time()
print(end - start)
java
public static void main(String[] args) {
long startTime=System.currentTimeMillis(); //获取开始时间
int sum = 0;
for(int i=0;i<10000000;i++){
sum +=i;
}
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println(endTime - startTime);
}
Go
package main
import "fmt"
import "time"
func main(){
sum := 0
var start = time.Now()
for i := 0; i< 10000000; i++ {
sum += i
}
fmt.Println(sum)
var end = time.Since(start)
fmt.Println(end)
}
C
#include <stdio.h>
#include <time.h>
int main() {
clock_t start, end;
double duration, sum;
start = clock();
for (int i = 0; i < 10000000; i++){
sum += i;
}
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("%f s", duration);
return 0;
}
我的电脑是magicbook,8G内存,运行的各自结果如下:
- go 7.9944ms
- c 0.036s
- python 1.96s
- java 16ms
关于python的结果早就料想到了,但另外3中语言居然超出了预料!!!