Golang: runtime.GOMAXPROCS 的设置问题。

2018-06-23 03:05:15 +08:00
 Flygar

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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/465179

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX