加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang设置CPU核数

发布时间:2020-12-16 18:36:56 所属栏目:大数据 来源:网络整理
导读:众所周知,golang低版本需要自己手动设置CPU核数,才能保证并发的执行 packagemainimport("errors""fmt""runtime""strconv""strings""testing")funcmain(){t:=testing.T{}TestSetCPU(t)}funcTestSetCPU(t*testing.T){currentCPU:=runtime.GOMAXPROCS(-1)maxC

众所周知,golang低版本需要自己手动设置CPU核数,才能保证并发的执行

packagemain

import(
	"errors"
	"fmt"
	"runtime"
	"strconv"
	"strings"
	"testing"
)

funcmain(){
	t:=&testing.T{}
	TestSetCPU(t)
}

funcTestSetCPU(t*testing.T){
	currentCPU:=runtime.GOMAXPROCS(-1)
	maxCPU:=runtime.NumCPU()
	halfCPU:=int(0.5*float32(maxCPU))
	ifhalfCPU<1{
		halfCPU=1
	}
	fori,test:=range[]struct{
		inputstring
		outputint
		shouldErrbool
	}{
		{"1",1,false},{"-1",currentCPU,true},{"0",{"100%",maxCPU,{"50%",halfCPU,{"110%",{"-10%",{"invalidinput",{"invalidinput%",{"9999",//overavailableCPU
	}{
		err:=setCPU(test.input)
		iftest.shouldErr&&err==nil{
			fmt.Printf("Test%d:Expectederror,buttherewasn'tany",i)
		}
		if!test.shouldErr&&err!=nil{
			fmt.Printf("Test%d:Expectednoerror,buttherewasone:%v",i,err)
		}
		ifactual,expected:=runtime.GOMAXPROCS(-1),test.output;actual!=expected{
			fmt.Printf("Test%d:GOMAXPROCSwas%dbutexpected%d",actual,expected)
		}else{
			fmt.Printf("--%v%vn",expected)
		}
		//teardown
		runtime.GOMAXPROCS(currentCPU)
	}
}

funcsetCPU(cpustring)error{
	varnumCPUint

	availCPU:=runtime.NumCPU()

	ifstrings.HasSuffix(cpu,"%"){
		//Percent
		varpercentfloat32
		pctStr:=cpu[:len(cpu)-1]
		pctInt,err:=strconv.Atoi(pctStr)
		iferr!=nil||pctInt<1||pctInt>100{
			returnerrors.New("invalidCPUvalue:percentagemustbebetween1-100")
		}
		percent=float32(pctInt)/100
		numCPU=int(float32(availCPU)*percent)
	}else{
		//Number
		num,err:=strconv.Atoi(cpu)
		iferr!=nil||num<1{
			returnerrors.New("invalidCPUvalue:provideanumberorpercentgreaterthan0")
		}
		numCPU=num
	}

	ifnumCPU>availCPU{
		numCPU=availCPU
	}

	runtime.GOMAXPROCS(numCPU)
	returnnil
}

关于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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读