并发循环如何理解???? go for

michael_xu · · 1345 次点击
上面的回复样式有问题,大致为: go 本身循环速度 < go func_name() < go func() 用go关键字后时间差距还是很大的。 但是不知道为什么C语言的循环会比go的还要慢。
#3
更多评论
你不好理解,就理解为多线程
#1
```go package main import "fmt" import "time" const ( //NUM = 10000000000000 //hang for process NUM = 1000000000 ) func f(from string) { for i := 0; i < NUM; i++ { i = i * 1 } } func main() { t0 := time.Now().UnixNano() f("direct") t := time.Now().UnixNano() go f("goroutine") t1 := time.Now().UnixNano() go func(msg string){ for i := 0; i < NUM; i++{ i = i * 1 } }("going") t2 := time.Now().UnixNano() fmt.Println("func:", t-t0, "ns, s:", (t-t0) / 1000000000) fmt.Println("go func:", t1-t, "ns, s:", (t1-t) / 1000000000) fmt.Println("go unknow func:", t2-t1, "ns, s:", (t2-t1) / 1000000000) } ``` ``` $$ time go run goroutines2.go func: 1048079427 ns, s: 1 go func: 12735 ns, s: 0 go unknow func: 1293 ns, s: 0 real 0m1.366s user 0m1.087s sys 0m0.067s ``` $ cat run.c ```c #include <string.h> #include <stdio.h> int main(){ int i; for(i=0; i < 1000000000; i++){ i = 1*i; } return 1; } ``` ``` $ time ./a.out real 0m3.970s user 0m3.030s sys 0m0.008s ```
#2