From eaa9494b71c046227264359beeaf80ddd4296ecf Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 29 Jun 2023 15:50:02 +0200 Subject: [PATCH] pkg/fileutils: GetTotalUsedFds: reduce allocations Use File.Readdirnames instead of os.ReadDir, as we're only interested in the number of files, and results don't have to be sorted. Before: BenchmarkGetTotalUsedFds-5 149272 7896 ns/op 945 B/op 20 allocs/op After: BenchmarkGetTotalUsedFds-5 153517 7644 ns/op 408 B/op 10 allocs/op Signed-off-by: Sebastiaan van Stijn --- pkg/fileutils/fileutils_linux.go | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/pkg/fileutils/fileutils_linux.go b/pkg/fileutils/fileutils_linux.go index 37611c975c..ea8faecec0 100644 --- a/pkg/fileutils/fileutils_linux.go +++ b/pkg/fileutils/fileutils_linux.go @@ -3,6 +3,7 @@ package fileutils import ( "context" "fmt" + "io" "os" "github.com/containerd/containerd/log" @@ -11,10 +12,24 @@ import ( // GetTotalUsedFds Returns the number of used File Descriptors by // reading it via /proc filesystem. func GetTotalUsedFds() int { - if fds, err := os.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { - log.G(context.TODO()).Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) - } else { - return len(fds) + name := fmt.Sprintf("/proc/%d/fd", os.Getpid()) + f, err := os.Open(name) + if err != nil { + log.G(context.TODO()).WithError(err).Error("Error listing file descriptors") + return -1 } - return -1 + defer f.Close() + + var fdCount int + for { + names, err := f.Readdirnames(100) + fdCount += len(names) + if err == io.EOF { + break + } else if err != nil { + log.G(context.TODO()).WithError(err).Error("Error listing file descriptors") + return -1 + } + } + return fdCount }