C语言:
[root@localhost efficient]# cat calc_c.c
#include<stdio.h>
#include<time.h>
int main(char** argv, char argc)
{
int second1,second2;
long long i;
long long count;
second1 = time((time_t*)NULL);
count = 0;
for (i = 0 ; i < 9000000000ll; i++){
count += i;
}
second2 = time((time_t*)NULL);
printf("cost:%d,count:%lld\n", second2 - second1, count);
return 0;
}
[root@localhost efficient]# make calc_c
cc calc_c.c -o calc_c
[root@localhost efficient]# ./calc_c
cost:57,count:3606511848080896768
golang:
[root@localhost efficient]# cat calc_go.go
package main
import "fmt"
import "time"
func main(){
t1 := time.Now()
count :=int64(0)
max := int64(9000000000)
for i :=int64(0); i< max; i++{
count += i
}
t2 := time.Now()
fmt.Printf("cost:%d,count:%d\n",t2.Sub(t1)/1000000000,count)
}
[root@localhost efficient]# go build calc_go.go
[root@localhost efficient]# ./calc_go
cost:52,count:3606511848080896768
基本一致,c用时57s,go用时52s。
下面加入简单Coroutine尝试
[root@localhost efficient]# cat calc_coroutine.go
package main
import "fmt"
import "runtime"
import "time"
func run(i,n int64 ,ch chan int64){
count := int64(0)
for i := int64(i); i < n; i++ {
count = count +i
}
ch <- count
}
func main(){
t1 := time.Now()
NCPU := runtime.NumCPU()
fmt.Printf("NCPU:%d\n",NCPU)
runtime.GOMAXPROCS(NCPU)
chs := make([] chan int64,NCPU)
for i :=int64(0); i < int64(NCPU); i++{
chs[i] = make(chan int64)
n := int64(9000000000)/int64(NCPU)
go run(i*n, (i+1)*n,chs[i])
}
count := int64(0)
for i :=0; i < NCPU;i++{
t := <- chs[i]
count = count +t
}
t2 := time.Now()
fmt.Printf("cpu num:%d,cost:%d,count:%d\n",NCPU,t2.Sub(t1)/1000000000,count)
}
[root@localhost efficient]# go build calc_coroutine.go
[root@localhost efficient]# ./calc_coroutine
NCPU:2
cpu num:2,cost:34,count:3606511848080896768
用时34s,确实提高了,关键是实现很简单
版权声明:本文为Tank_War原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。