猿问

尝试并行化的速度不够快

我阅读了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

使用戈鲁丁确实可以加快速度,但还不够。我预计它的速度会接近两倍。我的代码和/或理解有什么问题?我怎样才能接近两倍的速度?


一只甜甜圈
浏览 96回答 1
1回答

倚天杖

并行化功能强大,但很难在如此小的计算负载下看到。下面是一些结果差异较大的示例代码:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math"&nbsp; &nbsp; "runtime"&nbsp; &nbsp; "time")func calctest(nCPU int) {&nbsp; &nbsp; fmt.Println("Routines:", nCPU)&nbsp; &nbsp; ch := make(chan float64, nCPU)&nbsp; &nbsp; startTime := time.Now()&nbsp; &nbsp; a := 0.0&nbsp; &nbsp; b := 1.0&nbsp; &nbsp; n := 100000.0&nbsp; &nbsp; deltax := (b - a) / n&nbsp; &nbsp; stepPerCPU := n / float64(nCPU)&nbsp; &nbsp; for start := 0.0; start < n; {&nbsp; &nbsp; &nbsp; &nbsp; stop := start + stepPerCPU&nbsp; &nbsp; &nbsp; &nbsp; go f(start, stop, a, deltax, ch)&nbsp; &nbsp; &nbsp; &nbsp; start = stop&nbsp; &nbsp; }&nbsp; &nbsp; integral := 0.0&nbsp; &nbsp; for i := 0; i < nCPU; i++ {&nbsp; &nbsp; &nbsp; &nbsp; integral += <-ch&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(time.Now().Sub(startTime))&nbsp; &nbsp; fmt.Println(deltax * integral)}func f(start, stop, a, deltax float64, ch chan float64) {&nbsp; &nbsp; result := 0.0&nbsp; &nbsp; for i := start; i < stop; i++ {&nbsp; &nbsp; &nbsp; &nbsp; result += math.Sqrt(a + deltax*(i+0.5))&nbsp; &nbsp; }&nbsp; &nbsp; ch <- result}func main() {&nbsp; &nbsp; nCPU := runtime.NumCPU()&nbsp; &nbsp; calctest(nCPU)&nbsp; &nbsp; fmt.Println("")&nbsp; &nbsp; calctest(1)}这是我得到的结果:Routines: 8853.181µsRoutines: 12.031358ms
随时随地看视频慕课网APP

相关分类

Go
我要回答