github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/sys/cpu.go (about)

     1  // Package sys provides methods to read system information
     2  /*
     3   * Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
     4   */
     5  package sys
     6  
     7  import (
     8  	"os"
     9  	"runtime"
    10  
    11  	"github.com/NVIDIA/aistore/cmn/nlog"
    12  )
    13  
    14  const maxProcsEnvVar = "GOMAXPROCS"
    15  
    16  type LoadAvg struct {
    17  	One, Five, Fifteen float64
    18  }
    19  
    20  var (
    21  	contCPUs      int
    22  	containerized bool
    23  )
    24  
    25  func init() {
    26  	contCPUs = runtime.NumCPU()
    27  	if containerized = isContainerized(); containerized {
    28  		if c, err := containerNumCPU(); err == nil {
    29  			contCPUs = c
    30  		} else {
    31  			nlog.Errorln(err)
    32  		}
    33  	}
    34  }
    35  
    36  func Containerized() bool { return containerized }
    37  func NumCPU() int         { return contCPUs }
    38  
    39  // SetMaxProcs sets GOMAXPROCS = NumCPU unless already overridden via Go environment
    40  func SetMaxProcs() {
    41  	if val, exists := os.LookupEnv(maxProcsEnvVar); exists {
    42  		nlog.Warningf("GOMAXPROCS is set via Go environment %q: %q", maxProcsEnvVar, val)
    43  		return
    44  	}
    45  	maxprocs := runtime.GOMAXPROCS(0)
    46  	ncpu := NumCPU()
    47  	if maxprocs > ncpu {
    48  		nlog.Warningf("Reducing GOMAXPROCS (%d) to %d (num CPUs)", maxprocs, ncpu)
    49  		runtime.GOMAXPROCS(ncpu)
    50  	}
    51  }