登录
首页 >  Golang >  Go问答

尝试并行化效率不高

来源:stackoverflow

时间:2024-02-18 08:00:24 140浏览 收藏

大家好,今天本人给大家带来文章《尝试并行化效率不高》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我了解了 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

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


正确答案


并行化很强大,但是在如此小的计算负载下很难看到。下面是一些示例代码,结果差异较大:

package main

import (
    "fmt"
    "math"
    "runtime"
    "time"
)

func calctest(ncpu int) {
    fmt.println("routines:", ncpu)
    ch := make(chan float64, ncpu)
    starttime := time.now()
    a := 0.0
    b := 1.0
    n := 100000.0
    deltax := (b - a) / n

    steppercpu := n / float64(ncpu)
    for start := 0.0; start < n; {
        stop := start + steppercpu
        go f(start, stop, a, deltax, ch)
        start = stop
    }

    integral := 0.0
    for i := 0; i < ncpu; i++ {
        integral += <-ch
    }

    fmt.println(time.now().sub(starttime))
    fmt.println(deltax * integral)
}

func f(start, stop, a, deltax float64, ch chan float64) {
    result := 0.0
    for i := start; i < stop; i++ {
        result += math.sqrt(a + deltax*(i+0.5))
    }
    ch <- result
}

func main() {
    ncpu := runtime.numcpu()
    calctest(ncpu)
    fmt.println("")
    calctest(1)
}

这是我得到的结果:

Routines: 8
853.181µs

Routines: 1
2.031358ms

今天关于《尝试并行化效率不高》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>