
老哥们,我把代码中的 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. 1 Carseason 2018-06-23 03:08:54 +08:00 via iPhone 计算太短了,尝试 a 大一点看看.多测试几次做对比 |
2 Flygar OP @Carseason #1 我把 a 改成了 5000, 发现使用默认 CPU(4 个)要比使用使用 1 个 CPU 要慢 16s. ???哇!这也太恐怖啦吧 |
4 darrh00 2018-06-23 03:31:59 +08:00 多核不一定会快,要看你程序到底能不能并行, 你这里用了一个 channel,瓶颈就在这里,放在多核上跑反而会变慢 建议看一下 rob pike 的 Concurrency is not parallelism http://talks.golang.org/2012/waza.slide |
5 elvodn 2018-06-23 03:48:14 +08:00 就算是万核你也只有一个 stdout 啊, 最后还是单线程输出到屏幕上。 把 `fmt.Printf("%d\n ", i)` 注释掉,改为其他运算 |
7 heimeil 2018-06-23 09:18:42 +08:00 stdout 只有一个,并发访问同一资源产生了数据竞争,大部分时间都花在了同步锁上。 |