1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Use functions from x/sys/unix to get number of CPUs on Linux

Use Getpid and SchedGetaffinity from golang.org/x/sys/unix to get the
number of CPUs in numCPU on Linux.

Signed-off-by: Tobias Klauser <tklauser@distanz.ch>
This commit is contained in:
Tobias Klauser 2019-06-18 19:26:56 +02:00
parent 882e26a4a8
commit ba8a15694a
3 changed files with 15 additions and 24 deletions

View file

@ -2,7 +2,6 @@ package sysinfo // import "github.com/docker/docker/pkg/sysinfo"
import ( import (
"runtime" "runtime"
"unsafe"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -14,23 +13,15 @@ import (
// Returns 0 on errors. Use |runtime.NumCPU| in that case. // Returns 0 on errors. Use |runtime.NumCPU| in that case.
func numCPU() int { func numCPU() int {
// Gets the affinity mask for a process: The very one invoking this function. // Gets the affinity mask for a process: The very one invoking this function.
pid, _, _ := unix.RawSyscall(unix.SYS_GETPID, 0, 0, 0) pid := unix.Getpid()
var mask [1024 / 64]uintptr var mask unix.CPUSet
_, _, err := unix.RawSyscall(unix.SYS_SCHED_GETAFFINITY, pid, uintptr(len(mask)*8), uintptr(unsafe.Pointer(&mask[0]))) err := unix.SchedGetaffinity(pid, &mask)
if err != 0 { if err != nil {
return 0 return 0
} }
// For every available thread a bit is set in the mask. return mask.Count()
ncpu := 0
for _, e := range mask {
if e == 0 {
continue
}
ncpu += int(popcnt(uint64(e)))
}
return ncpu
} }
// NumCPU returns the number of CPUs which are currently online // NumCPU returns the number of CPUs which are currently online

View file

@ -13,6 +13,16 @@ var (
getProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask") getProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
) )
// Returns bit count of 1, used by NumCPU
func popcnt(x uint64) (n byte) {
x -= (x >> 1) & 0x5555555555555555
x = (x>>2)&0x3333333333333333 + x&0x3333333333333333
x += x >> 4
x &= 0x0f0f0f0f0f0f0f0f
x *= 0x0101010101010101
return byte(x >> 56)
}
func numCPU() int { func numCPU() int {
// Gets the affinity mask for a process // Gets the affinity mask for a process
var mask, sysmask uintptr var mask, sysmask uintptr

View file

@ -146,13 +146,3 @@ func isCpusetListAvailable(provided, available string) (bool, error) {
} }
return true, nil return true, nil
} }
// Returns bit count of 1, used by NumCPU
func popcnt(x uint64) (n byte) {
x -= (x >> 1) & 0x5555555555555555
x = (x>>2)&0x3333333333333333 + x&0x3333333333333333
x += x >> 4
x &= 0x0f0f0f0f0f0f0f0f
x *= 0x0101010101010101
return byte(x >> 56)
}