学习了一段时间的golang,想通过计算100000以内的素数个数测试下Golang的运行速率,并与C++和Python进行对比,具体实现如下:
Golang:
package main
import (
"fmt"
"time"
)
func main() {
var count, state int
start := time.Now()
for outer := 2; outer < 100000; outer++ {
state = 0
for inner := 2; inner < outer; inner++ {
if outer % inner == 0 {
state = 1
break
}
}
if state == 0 {
count++
}
}
fmt.Println(count, " primes in 100000")
elapse := time.Since(start)
fmt.Println(elapse, "cost")
}
Python:
import time
count = 0
start = time.time()
for i in range(2, 100000):
state = 0
for j in range(2, i):
if i % j == 0:
state = 1
break
if not state:
count += 1
elapse = time.time() - start
print(f'{count} primes in 100000')
print(f'{elapse}s cost')
C++:
#include<iostream>
#include<ctime>
using namespace std;
int main() {
clock_t start = clock();
int count = 0, state = 0;
for (int outer = 2; outer < 100000; outer++) {
state = 0;
for (int inner = 2; inner < outer; inner++) {
if (outer % inner == 0) {
state = 1;
break;
}
}
if (state == 0) {
count++;
}
}
cout << count << " primes in 100000" << endl;
clock_t end = clock();
cout << (double(end) - double(start)) / CLOCKS_PER_SEC << "s cost" << endl;
return 0;
}
运行一下:
Golang:
Python:
C++:
可以看到Go的运行效率更接近C++,均比Python高了一个量级