Verifying Processors Used by a Golang Program
When executing a Golang program, it's crucial to understand the number of processors it utilizes. This article addresses this issue, providing a comprehensive explanation and a coding solution.
Runtime.GOMAXPROCS() controls the maximum number of logical processors a Go program can access, while Runtime.NumCPU() returns the available logical processors. However, the maximum parallelism is limited by the minimum of these two values.
To verify the number of processors in use, modify the code as follows:
package main import ( "fmt" "runtime" "sync" ) var wg sync.WaitGroup func doTasks() { fmt.Println(" Doing task ") for ji := 1; ji < 100000000; ji++ { for io := 1; io < 10; io++ { // Some computations } } runtime.Gosched() wg.Done() } func main() { wg.Add(1) runtime.GOMAXPROCS(1) // or 2 or 4 go doTasks() doTasks() wg.Wait() fmt.Println("Maximum processors:", runtime.GOMAXPROCS(0)) fmt.Println("Available logical processors:", runtime.NumCPU()) fmt.Println("Maximum parallelism:", runtime.MaxParallelism()) }
This enhanced code adds functionalities to display the Runtime.GOMAXPROCS(), Runtime.NumCPU(), and Runtime.MaxParallelism() values, providing a clear view of the program's processor usage.
The above is the detailed content of How Many Processors Does My Go Program Actually Use?. For more information, please follow other related articles on the PHP Chinese website!