The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Flygar

Golang: runtime.GOMAXPROCS 的设置问题。

  •  
  •   Flygar · Jun 23, 2018 · 3021 views
    This topic created in 2893 days ago, the information mentioned may be changed or developed.

    老哥们,我把代码中的 runtime.GOMAXPROCS(1) 注释掉了,可是程序运行下来的时间根本没减少,这是为什么?
    真是百思不得骑呐

    package main
    
    import (
    	"fmt"
    	"time"
    	"runtime"
    )
    
    var quit chan int = make(chan int)
    
    func loop() {
    	for i := 0; i < 10000; i++ {
    		fmt.Printf("%d\n ", i)
    	}
    	quit <- 0
    }
    
    func main() {
    	fmt.Println(runtime.NumCPU())
    	time.Sleep(time.Second)
    	a := 500
    	t1 := time.Now()
    	runtime.GOMAXPROCS(1)  //单核跑和把这句话注释吊(使用默认 CPU 个数)跑下来时间没差,这是为什么?
    
    	for i := 1; i <= a; i++ {
    		go loop()
    	}
    
    	for i := 0; i < a; i++ {
    		<-quit
    	}
    	elapsed := time.Since(t1)
    	fmt.Println("运行时间:", elapsed)
    }
    
    // 下面是 GOMAXPROCS 的说明
    
    // GOMAXPROCS sets the maximum number of CPUs that can be executing
    // simultaneously and returns the previous setting. If n < 1, it does not
    // change the current setting.
    // The number of logical CPUs on the local machine can be queried with NumCPU.
    // This call will go away when the scheduler improves.
    
    8 replies    2018-06-23 13:52:35 +08:00
    Carseason
        1
    Carseason  
       Jun 23, 2018 via iPhone
    计算太短了,尝试 a 大一点看看.多测试几次做对比
    Flygar
        2
    Flygar  
    OP
       Jun 23, 2018
    @Carseason #1 我把 a 改成了 5000, 发现使用默认 CPU(4 个)要比使用使用 1 个 CPU 要慢 16s. ???哇!这也太恐怖啦吧
    Flygar
        3
    Flygar  
    OP
       Jun 23, 2018
    @Unknwon ,@h4lbhg1G ,@ysc3839 .强行艾特
    darrh00
        4
    darrh00  
       Jun 23, 2018   ❤️ 2
    多核不一定会快,要看你程序到底能不能并行,
    你这里用了一个 channel,瓶颈就在这里,放在多核上跑反而会变慢
    建议看一下 rob pike 的 Concurrency is not parallelism http://talks.golang.org/2012/waza.slide
    elvodn
        5
    elvodn  
       Jun 23, 2018   ❤️ 1
    就算是万核你也只有一个 stdout 啊, 最后还是单线程输出到屏幕上。
    把 `fmt.Printf("%d\n ", i)` 注释掉,改为其他运算
    ysc3839
        6
    ysc3839  
       Jun 23, 2018 via Android
    @Flygar #3 你找错人了吧?我不懂 Golang。
    heimeil
        7
    heimeil  
       Jun 23, 2018   ❤️ 1
    stdout 只有一个,并发访问同一资源产生了数据竞争,大部分时间都花在了同步锁上。
    Flygar
        8
    Flygar  
    OP
       Jun 23, 2018
    @elvodn @heimeil 感谢 2 位大大,十分感谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   886 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 22:22 · PVG 06:22 · LAX 15:22 · JFK 18:22
    ♥ Do have faith in what you're doing.