测试go并发编程
package main
import (
"fmt"
"time"
)
func sum(values []int, resultChan chan int) {
sum := 0
for _, value := range values {
sum += value
}
resultChan <- sum
}
func main() {
var arr [10000000]int
for i := 0; i < 10000000; i++ {
arr[i] = i
}
result2Chan := make(chan int)
t_begin := time.Now().UnixNano() / 1e6
fmt.Println("开始并发时间:", t_begin)
go sum(arr[:len(arr)/2], result2Chan)
go sum(arr[len(arr)/2:], result2Chan)
sum3, sum4 := <-result2Chan, <-result2Chan
fmt.Println("Result is :", sum3, sum4, sum3+sum4)
t_end := time.Now().UnixNano() / 1e6
fmt.Println("并发结束时间:", t_end)
result3Chan := make(chan int)
go sum(arr[:10000000], result3Chan)
sum5 := <-result3Chan
fmt.Println("Result is :", sum5)
t_end2 := time.Now().UnixNano() / 1e6
fmt.Println("单线程结束时间:", t_end2)
}
运行结果:
开始并发时间: 1572315066689
Result is : 37499997500000 12499997500000 49999995000000
并发结束时间: 1572315066693
Result is : 49999995000000
单线程结束时间: 1572315066702