Skip to content

Commit

Permalink
Cgroup2: Reduce allocations in readHugeTlbStats
Browse files Browse the repository at this point in the history
In the journey of continuing to reduce allocations in manager.Stat,
this sets its eyes on optimizing readHugeTlbStats. The number of allocs
shaved off here is tied to the number of files in the cgroup directory
as f.Readdir(-1) was being called which returns a slice of interfaces.
The change here is to just swap to f.Readdirnames as we were only using
the os.FileInfo's to call Name(), and that's what Readdirnames returns us.

Signed-off-by: Danny Canter <danny@dcantah.dev>
  • Loading branch information
dcantah committed Apr 7, 2023
1 parent 766cb4b commit 0391449
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions cgroup2/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,41 +390,55 @@ func systemdUnitFromPath(path string) string {
func readHugeTlbStats(path string) []*stats.HugeTlbStat {
usage := []*stats.HugeTlbStat{}
keyUsage := make(map[string]*stats.HugeTlbStat)

f, err := os.Open(path)
if err != nil {
return usage
}
files, err := f.Readdir(-1)

files, err := f.Readdirnames(-1)
f.Close()
if err != nil {
return usage
}

buf := make([]byte, 32)
for _, file := range files {
if strings.Contains(file.Name(), "hugetlb") &&
(strings.HasSuffix(file.Name(), "max") || strings.HasSuffix(file.Name(), "current")) {
var hugeTlb *stats.HugeTlbStat
var ok bool
fileName := strings.Split(file.Name(), ".")
if strings.Contains(file, "hugetlb") &&
(strings.HasSuffix(file, "max") || strings.HasSuffix(file, "current")) {
var (
hugeTlb *stats.HugeTlbStat
ok bool
)
fileName := strings.Split(file, ".")
pageSize := fileName[1]
if hugeTlb, ok = keyUsage[pageSize]; !ok {
hugeTlb = &stats.HugeTlbStat{}
}
hugeTlb.Pagesize = pageSize
out, err := os.ReadFile(filepath.Join(path, file.Name()))

f, err := os.Open(filepath.Join(path, file))
if err != nil {
continue
}
defer f.Close()

n, err := f.Read(buf)
if err != nil {
continue
}

var value uint64
stringVal := strings.TrimSpace(string(out))
stringVal := strings.TrimSpace(string(buf[:n]))
if stringVal == "max" {
value = math.MaxUint64
} else {
value, err = strconv.ParseUint(stringVal, 10, 64)
if err != nil {
continue
}
}
if err != nil {
continue
}

switch fileName[2] {
case "max":
hugeTlb.Max = value
Expand Down

0 comments on commit 0391449

Please sign in to comment.