Home >Backend Development >Golang >Detailed explanation of Golang cpu usage settings

Detailed explanation of Golang cpu usage settings

藏色散人
藏色散人forward
2021-06-11 11:54:282676browse

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 machine CPU has 4 cores, and the test code opens 4 goroutines. From the test results, it can be seen that all 4 cores are fully running.

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) int

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.

Set the number of CPUs used during concurrent execution

For 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 process

Currently 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:

Test machine: MAC CPU 8 core

Version: go version go1.13 darwin/amd64

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%

2. Use GOMAXPROCS to set up CPU

8 goroutines
- Set to use only 1 core, and the CPU usage can reach up to 100%

- Set to use only 2 cores, and the CPU usage can reach 200%


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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete