numcpu_windows.go 849 B

1234567891011121314151617181920212223242526272829303132333435
  1. package sysinfo
  2. import (
  3. "runtime"
  4. "unsafe"
  5. "golang.org/x/sys/windows"
  6. )
  7. var (
  8. kernel32 = windows.NewLazySystemDLL("kernel32.dll")
  9. getCurrentProcess = kernel32.NewProc("GetCurrentProcess")
  10. getProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
  11. )
  12. func numCPU() int {
  13. // Gets the affinity mask for a process
  14. var mask, sysmask uintptr
  15. currentProcess, _, _ := getCurrentProcess.Call()
  16. ret, _, _ := getProcessAffinityMask.Call(currentProcess, uintptr(unsafe.Pointer(&mask)), uintptr(unsafe.Pointer(&sysmask)))
  17. if ret == 0 {
  18. return 0
  19. }
  20. // For every available thread a bit is set in the mask.
  21. ncpu := int(popcnt(uint64(mask)))
  22. return ncpu
  23. }
  24. // NumCPU returns the number of CPUs which are currently online
  25. func NumCPU() int {
  26. if ncpu := numCPU(); ncpu > 0 {
  27. return ncpu
  28. }
  29. return runtime.NumCPU()
  30. }