Debian Codegraph @

cpuset/numcpu.go

raw
1 /*
2 Copyright 2026 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package cpuset
18
19 import (
20 "fmt"
21 "os"
22 "strings"
23 )
24
25 // onlineCPUsPath is the sysfs file listing the host's online CPUs. It is a
26 // variable so tests can point it at a fixture.
27 var onlineCPUsPath = "/sys/devices/system/cpu/online"
28
29 // NumCPU returns the number of CPUs that are online on the host, read from
30 // /sys/devices/system/cpu/online. The file holds a cpu list such as "0-3,8-11";
31 // see https://docs.kernel.org/admin-guide/cputopology.html for the format.
32 //
33 // Unlike runtime.NumCPU, the result is not affected by the calling process's
34 // CPU affinity (its cgroup cpuset), so it reflects the whole machine. This is
35 // what you want when sizing a host-wide resource by CPU count.
36 //
37 // NumCPU returns an error if the online file cannot be read or parsed, for
38 // example on non-Linux platforms. Callers that need a value regardless should
39 // fall back to runtime.NumCPU.
40 func NumCPU() (int, error) {
41 data, err := os.ReadFile(onlineCPUsPath)
42 if err != nil {
43 return 0, err
44 }
45 set, err := Parse(strings.TrimSpace(string(data)))
46 if err != nil {
47 return 0, fmt.Errorf("parsing %q: %w", onlineCPUsPath, err)
48 }
49 return set.Size(), nil
50 }