Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: how to verify number of processors on which a Go program is running

I am new to Google Go (Golang). My question is related to this post What exactly does runtime.Gosched do?. 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()
}
like image 620
user984260 Avatar asked Nov 05 '12 15:11

user984260


People also ask

What is Gomaxprocs?

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. The number of logical CPUs on the local machine can be queried with NumCPU. This call will go away when the scheduler improves.

What is Go runtime?

The Go runtime in the flexible environment is the software stack responsible for building and running your code. To choose the Go runtime in the flexible environment, add two lines to your app. yaml file.


1 Answers

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
}
like image 187
Matt Joiner Avatar answered Sep 28 '22 07:09

Matt Joiner