// Check the global runnable queue once in a while to ensure fairness.// Otherwise two goroutines can completely occupy the local runqueue// by constantly respawning each other.ifpp.schedtick%61==0&&!sched.runq.empty(){lock(&sched.lock)gp:=globrunqget()unlock(&sched.lock)ifgp!=nil{returngp,false,false}}
~/project/go_demo 7s
❯ go test -bench=. ./...
goos: linux
goarch: amd64
pkg: gomaxprocs-bench
cpu: AMD Ryzen 7 6800H with Radeon Graphics
BenchmarkCPUBound_GOMAXPROCS_1-16 100 15270612 ns/op
testing: BenchmarkCPUBound_GOMAXPROCS_1-16 left GOMAXPROCS set to 1
BenchmarkCPUBound_GOMAXPROCS_4-16 279 4803904 ns/op
testing: BenchmarkCPUBound_GOMAXPROCS_4-16 left GOMAXPROCS set to 4
BenchmarkCPUBound_GOMAXPROCS_8-16 352 3154692 ns/op
testing: BenchmarkCPUBound_GOMAXPROCS_8-16 left GOMAXPROCS set to 8
BenchmarkCPUBound_GOMAXPROCS_16-16 483 2153030 ns/op
BenchmarkCPUBound_GOMAXPROCS_32-16 482 2204711 ns/op
testing: BenchmarkCPUBound_GOMAXPROCS_32-16 left GOMAXPROCS set to 32
BenchmarkIOBound_50ms_GOMAXPROCS_1-16 22 50526068 ns/op
testing: BenchmarkIOBound_50ms_GOMAXPROCS_1-16 left GOMAXPROCS set to 1
BenchmarkIOBound_50ms_GOMAXPROCS_4-16 86 13001928 ns/op
testing: BenchmarkIOBound_50ms_GOMAXPROCS_4-16 left GOMAXPROCS set to 4
BenchmarkIOBound_50ms_GOMAXPROCS_8-16 171 6604883 ns/op
testing: BenchmarkIOBound_50ms_GOMAXPROCS_8-16 left GOMAXPROCS set to 8
BenchmarkIOBound_50ms_GOMAXPROCS_16-16 356 3352537 ns/op
BenchmarkIOBound_50ms_GOMAXPROCS_32-16 711 1676945 ns/op
testing: BenchmarkIOBound_50ms_GOMAXPROCS_32-16 left GOMAXPROCS set to 32
PASS
ok gomaxprocs-bench 16.211s
结果很明显,对于 CPU 密集型任务 GOMAXPROCS 等于实际核心数时性能最佳,过多反而导致性能下降。但高 I/O 场景,GOMAXPROCS 大于实际 CPU 核心数确实可以提升性能。