Golang:如何验证Go程序运行在多少个处理器上

huangapple go评论80阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;runtime&quot;
	&quot;sync&quot;
)

var wg sync.WaitGroup

func doTasks() {
	fmt.Println(&quot; Doing task &quot;)
	for ji := 1; ji &lt; 100000000; ji++ {
		for io := 1; io &lt; 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 &lt; 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."

huangapple
  • 本文由 发表于 2012年11月5日 23:03:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/13234749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定