From 03914495825c323548514c366116668293d479bf Mon Sep 17 00:00:00 2001 From: Danny Canter Date: Fri, 7 Apr 2023 11:56:53 -0700 Subject: [PATCH] Cgroup2: Reduce allocations in readHugeTlbStats 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 --- cgroup2/utils.go | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/cgroup2/utils.go b/cgroup2/utils.go index a9875cb0..fbbc93bf 100644 --- a/cgroup2/utils.go +++ b/cgroup2/utils.go @@ -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