4

We all know that runtime.GOMAXPROCS is set to CPU core number by default, what if this property has been set too large?

  1. Will program have more context switches?
  2. Will garbage collector be triggered more frequently?
icza
  • 389,944
  • 63
  • 907
  • 827
Yi Zheng
  • 61
  • 1
  • 4

1 Answers1

13

GOMAXPROCS is set to the number of available logical CPUs by default for a reason: this gives best performance in most cases.

GOMAXPROCS only limits the number of "active" threads, if a thread's goroutine gets blocked (e.g. by a syscall), a new thread might be started. There is no direct correclation, see Number of threads used by Go runtime.

If GOMAXPROCS is greater than the number of available CPUs, then there will be more active threads than CPU cores, which means active threads have to be "multiplexed" to the available processing units, so yes, there will be more context switches if there are more active threads than cores, which is not necessarily the case.

Garbage collections are not directly related to the number of threads, so you shouldn't worry about that. Quoting from package runtime:

The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. The runtime/debug package's SetGCPercent function allows changing this percentage at run time. See https://golang.org/pkg/runtime/debug/#SetGCPercent.

If you have more threads that don't allocate / release memory, that shouldn't effect how frequently collections are triggered.

There might be cases when setting GOMAXPROCS above the number of CPUs increases the performance of your app, but they are rare. Measure to find out if it helps in your case.

icza
  • 389,944
  • 63
  • 907
  • 827