Home >Backend Development >Golang >Detailed explanation of Golang cpu usage settings
The following tutorial column will give you a detailed explanation of the usage settings of Golang cpu. I hope it will be helpful to friends in need! For the following tests, the Go version used is 1.8.3Not set
If runtime.GOMAXPROCS is not called to set the CPU, Golang uses all cpu cores by default.
The test code is as follows:
package main func main() { go task() go task() go task() go task() select{} } func task(){ for { } }
Set CPU usage
func GOMAXPROCS(n int) intGOMAXPROCS 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.
Set the number of CPUs used during concurrent executionFor example, set to use only 1 core
runtime.GOMAXPROCS(1)
Set up to use only 2 cores
runtime.GOMAXPROCS(2)
The test code is as follows, set up only one core:
package main import ( "runtime" ) func main() { runtime.GOMAXPROCS(1) go task() go task() go task() go task() select{} } func task(){ for { } }
Sometimes, we often use:
runtime.GOMAXPROCS( runtime.NumCPU())func NumCPU() int NumCPU returns the number of logical CPUs usable by the current process.
The function returns the number of logical CPUs available for the current processCurrently tested, using this to set the CPU has the same effect as not calling GOMAXPROCS, that is, using Number of all CPU cores.
2020.1.1 Supplementary update
Latest test results:
1. Do not use GOMAXPROCS to set up CPU
8 goroutines, which can run up to 8 cores, and the CPU usage can reach up to 800%
8 goroutines
- Set to use only 1 core, and the CPU usage can reach up to 100%
That is to say, GOMAXPROCS can be used to set the program to use the most Number of CPU cores.
The above is the detailed content of Detailed explanation of Golang cpu usage settings. For more information, please follow other related articles on the PHP Chinese website!