执行环境:window7/64 , go1.4
在学习go的gorountine时执行的例子:
```
package main
import "fmt"
func sum(values [] int, resultChan chan int) {
sum := 0
for _, value := range values {
sum += value
}
resultChan <- sum // 将计算结果发送到channel中
}
func main() {
values := [] int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
resultChan := make(chan int, 2)
go sum(values[:len(values)/2], resultChan)
go sum(values[len(values)/2:], resultChan)
sum1, sum2 := <-resultChan, <-resultChan // 接收结果
fmt.Println("Result:", sum1, sum2, sum1 + sum2)
}
```
执行了三次:
```
1:[ `go run paracal.go` | done: 19.1530954s ]
Result: 15 40 55
2:[ `go run paracal.go` | done: 7.2924171s ]
Result: 15 40 55
3:[ `go run paracal.go` | done: 13.5667759s ]
Result: 15 40 55
```
谁能给深入揭示一下执行过程,并分析一下为什么执行了10以上的时间?
mac 10.10下面跑
直接run:
$ time go run tmp.go
Result: 15 40 55
real 0m0.159s
user 0m0.120s
sys 0m0.033s
编译后再run
$ time ./tmp
Result: 15 40 55
real 0m0.006s
user 0m0.001s
sys 0m0.003s
#8
更多评论