go - 为什么Go使用更多的CPU但不减少计算时间?

标签 go parallel-processing

我编写了一个简单的Go程序,在许多goroutine中添加数字。
当我增加goroutine的数量时,该程序将使用更多的CPU,并且我希望计算时间会缩短。 1、2或4个goroutine确实如此,但是当我尝试8个goroutine时,持续时间与4相同(我在8个CPU处理器的i5-8265U上运行测试)。
你能跟我解释一下吗?
代码:

package main

import (
    "fmt"
    "time"
)

// Sum returns n by calculating 1+1+1+..
func Sum(n int64) int64 {
    ret := int64(0)
    for i := int64(0); i < n; i++ {
        ret += 1
    }
    return ret
}

func main() {
    n := int64(30000000000) // 30e9
    sum := int64(0)
    beginTime := time.Now()

    nWorkers := 4
    sumChan := make(chan int64, nWorkers)
    for i := 0; i < nWorkers; i++ {
        go func() { sumChan <- Sum(n / int64(nWorkers)) }()
    }
    for i := 0; i < nWorkers; i++ {
        sum += <-sumChan
    }

    fmt.Println("dur:", time.Since(beginTime))
    fmt.Println("sum:", sum)

    // Results on Intel Core i5-8265U (nWorkers,dur):
    // (1, 8s), (2, 4s), (4, 2s), (8, 2s). Why 8 CPUs still need 2s?
}

最佳答案

我在8个CPU的处理器i5-8265U上进行了测试

The i5-8265U is not an 8-core CPU, it's a 4-core 8-threads CPU:它具有4个物理核心,每个核心可以通过hyperthreading同时运行2个线程。

HT的“性能优势”取决于工作负载,以及将一个线程的操作与另一个线程的计算“混合”的能力。这意味着,如果您的CPU负载很高,则超线程可能无法获得超过百分之几的运行时间,因此对总体性能的贡献不大。

此外,8265U的标称频率为1.6GHz,最大turbo值为3.9(4核为3.7)。包括超线程在内的CPU满载也可能会进一步降低“涡轮上限”。您必须在运行期间输入check the cpuinfo state才能看到。

关于go - 为什么Go使用更多的CPU但不减少计算时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60542559/

相关文章:

html - 需要在发起http响应后通知邮件发送状态

rest - 使用validator.v2根据不同字段的值验证字段

mysql - 数据库连接卡在 AWS Lambda 上

R:是否可以将 2000 万多行 CSV 的读取并行化/加速到 R 中?

python - numba - guvectorize 比 jit 快一点

html - r.From ["username"] 给出空值

go - 什么是 rune ?

r - R中并行计算的stdout和stderr

r - doParallel 而不是 apply

parallel-processing - 我可以利用并行化来使这段代码更快吗?