golang CPUコア数設定
2622 ワード
ご存じのように、golangの低バージョンでは、同時実行を保証するためにCPUコア数を手動で設定する必要があります.
golangの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.
package main
import (
"errors"
"fmt"
"runtime"
"strconv"
"strings"
"testing"
)
func main() {
t := &testing.T{}
TestSetCPU(t)
}
func TestSetCPU(t *testing.T) {
currentCPU := runtime.GOMAXPROCS(-1)
maxCPU := runtime.NumCPU()
halfCPU := int(0.5 * float32(maxCPU))
if halfCPU < 1 {
halfCPU = 1
}
for i, test := range []struct {
input string
output int
shouldErr bool
}{
{"1", 1, false},
{"-1", currentCPU, true},
{"0", currentCPU, true},
{"100%", maxCPU, false},
{"50%", halfCPU, false},
{"110%", currentCPU, true},
{"-10%", currentCPU, true},
{"invalid input", currentCPU, true},
{"invalid input%", currentCPU, true},
{"9999", maxCPU, false}, // over available CPU
} {
err := setCPU(test.input)
if test.shouldErr && err == nil {
fmt.Printf("Test %d: Expected error, but there wasn't any", i)
}
if !test.shouldErr && err != nil {
fmt.Printf("Test %d: Expected no error, but there was one: %v", i, err)
}
if actual, expected := runtime.GOMAXPROCS(-1), test.output; actual != expected {
fmt.Printf("Test %d: GOMAXPROCS was %d but expected %d", i, actual, expected)
} else {
fmt.Printf("-- %v %v
", actual, expected)
}
// teardown
runtime.GOMAXPROCS(currentCPU)
}
}
func setCPU(cpu string) error {
var numCPU int
availCPU := runtime.NumCPU()
if strings.HasSuffix(cpu, "%") {
// Percent
var percent float32
pctStr := cpu[:len(cpu)-1]
pctInt, err := strconv.Atoi(pctStr)
if err != nil || pctInt < 1 || pctInt > 100 {
return errors.New("invalid CPU value: percentage must be between 1-100")
}
percent = float32(pctInt) / 100
numCPU = int(float32(availCPU) * percent)
} else {
// Number
num, err := strconv.Atoi(cpu)
if err != nil || num < 1 {
return errors.New("invalid CPU value: provide a number or percent greater than 0")
}
numCPU = num
}
if numCPU > availCPU {
numCPU = availCPU
}
runtime.GOMAXPROCS(numCPU)
return nil
}
golangの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.