英文:
Golang: how to verify number of processors on which a Go program is running
问题
我是新来的Google Go(Golang)用户。我的问题与此帖子https://stackoverflow.com/q/13107958/984260有关。代码的结构如下所示。我的问题是,当我更改GOMAXPROCS中的处理器数量时,如何验证它正在运行的处理器数量。当我运行'top'命令时,它显示a.out进程,即使GOMAXPROCS大于1,它也只消耗100%或更少的资源。非常感谢您的帮助。
package main
import (
"fmt"
"runtime"
"sync"
)
var wg sync.WaitGroup
func doTasks() {
fmt.Println("正在执行任务")
for ji := 1; ji < 100000000; ji++ {
for io := 1; io < 10; io++ {
//一些计算
}
}
runtime.Gosched()
wg.Done()
}
func main() {
wg.Add(1)
runtime.GOMAXPROCS(1) // 或者2或4
go doTasks()
doTasks()
wg.Wait()
}
英文:
I am new to Google Go (Golang). My question is related to this post https://stackoverflow.com/q/13107958/984260. The structure of code is as copied below. My question, is that when I change the number of processor in GOMAXPROCS, how do I verify how many processors it is running on. When I do 'top', it shows a.out process which consumes 100% or less resources even when GOMAXPROCS is more than 1. I would be grateful for your help.
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()
}
答案1
得分: 36
进程可以同时运行的逻辑CPU的最大数量不超过runtime.GOMAXPROCS(0)
和runtime.NumCPU()
中的最小值。
func MaxParallelism() int {
maxProcs := runtime.GOMAXPROCS(0)
numCPU := runtime.NumCPU()
if maxProcs < numCPU {
return maxProcs
}
return numCPU
}
英文:
The largest number of logical CPUs the process can be running on at a given time is no more than the minimum of runtime.GOMAXPROCS(0)
and runtime.NumCPU()
.
func MaxParallelism() int {
maxProcs := runtime.GOMAXPROCS(0)
numCPU := runtime.NumCPU()
if maxProcs < numCPU {
return maxProcs
}
return numCPU
}
答案2
得分: 2
核心数量可以通过http://golang.org/pkg/runtime/#NumCPU查询。
文档中写道:“NumCPU返回本地机器上的逻辑CPU数量。”
英文:
The number of cores can be inquired by http://golang.org/pkg/runtime/#NumCPU.
The documentation says: "NumCPU returns the number of logical CPUs on the local machine."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论