我阅读了Go的并发模型,还看到了并发性和并行性之间的区别。为了测试并行执行,我编写了以下程序。
package main
import (
"fmt"
"runtime"
"time"
)
const count = 1e8
var buffer [count]int
func main() {
fmt.Println("GOMAXPROCS: ", runtime.GOMAXPROCS(0))
// Initialise with dummy value
for i := 0; i < count; i++ {
buffer[i] = 3
}
// Sequential operation
now := time.Now()
worker(0, count-1)
fmt.Println("sequential operation: ", time.Since(now))
// Attempt to parallelize
ch := make(chan int, 1)
now = time.Now()
go func() {
worker(0, (count/2)-1)
ch <- 1
}()
worker(count/2, count-1)
<-ch
fmt.Println("parallel operation: ", time.Since(now))
}
func worker(start int, end int) {
for i := start; i <= end; i++ {
task(i)
}
}
func task(index int) {
buffer[index] = 2 * buffer[index]
}
但问题是:结果不是很令人愉快。
GOMAXPROCS: 8
sequential operation: 206.85ms
parallel operation: 169.028ms
使用戈鲁丁确实可以加快速度,但还不够。我预计它的速度会接近两倍。我的代码和/或理解有什么问题?我怎样才能接近两倍的速度?
倚天杖
相关分类