【发布时间】:2016-03-19 16:14:09
【问题描述】:
我最近在朋友的推荐下开始学习围棋。到目前为止,我很喜欢它,但是我写了(我认为会是)轻量级并发功能的完美示例,并得到了令人惊讶的结果......所以我怀疑我做错了什么,或者我是误解了 goroutine 的昂贵程度。我希望这里的一些地鼠可以提供见解。
我使用 goroutine 和简单的同步执行在 Go 中编写了 Chudnovsky 算法。我假设,每个计算都独立于其他计算,并发运行至少会快一点。
注意:我在第 5 代 i7 上运行它,所以如果按照我所说的将 goroutine 多路复用到线程上,这应该是并发 和 并行的。
package main
import (
"fmt"
"math"
"strconv"
"time"
)
func main() {
var input string
var sum float64
var pi float64
c := make(chan float64)
fmt.Print("How many iterations? ")
fmt.Scanln(&input)
max,err := strconv.Atoi(input)
if err != nil {
panic("You did not enter a valid integer")
}
start := time.Now() //start timing execution of concurrent routine
for i := 0; i < max; i++ {
go chudnovskyConcurrent(i,c)
}
for i := 0; i < max; i++ {
sum += <-c
}
end := time.Now() //end of concurrent routine
fmt.Println("Duration of concurrent calculation: ",end.Sub(start))
pi = 1/(12*sum)
fmt.Println(pi)
start = time.Now() //start timing execution of syncronous routine
sum = 0
for i := 0; i < max; i++ {
sum += chudnovskySync(i)
}
end = time.Now() //end of syncronous routine
fmt.Println("Duration of synchronous calculation: ",end.Sub(start))
pi = 1/(12*sum)
fmt.Println(pi)
}
func chudnovskyConcurrent(i int, c chan<- float64) {
var numerator float64
var denominator float64
ifloat := float64(i)
iun := uint64(i)
numerator = math.Pow(-1, ifloat) * float64(factorial(6*iun)) * (545140134*ifloat+13591409)
denominator = float64(factorial(3*iun)) * math.Pow(float64(factorial(iun)),3) * math.Pow(math.Pow(640320,3),ifloat+0.5)
c <- numerator/denominator
}
func chudnovskySync(i int) (r float64) {
var numerator float64
var denominator float64
ifloat := float64(i)
iun := uint64(i)
numerator = math.Pow(-1, ifloat) * float64(factorial(6*iun)) * (545140134*ifloat+13591409)
denominator = float64(factorial(3*iun)) * math.Pow(float64(factorial(iun)),3) * math.Pow(math.Pow(640320,3),ifloat+0.5)
r = numerator/denominator
return
}
func factorial(n uint64) (res uint64) {
if ( n > 0 ) {
res = n * factorial(n-1)
return res
}
return 1
}
这是我的结果:
How many iterations? 20
Duration of concurrent calculation: 573.944µs
3.1415926535897936
Duration of synchronous calculation: 63.056µs
3.1415926535897936
【问题讨论】:
-
goroutine 很便宜,它们不是免费的。
go version命令的输出是什么? -
go 版本 go1.6 linux/amd64
-
BUG ALERT:您的示例,20 次迭代,溢出了您的阶乘函数。
标签: go concurrency parallel-processing