Pārlūkot izejas kodu

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 <github@gone.nl>
Sebastiaan van Stijn 2 gadi atpakaļ
vecāks
revīzija
eaa9494b71
1 mainītis faili ar 20 papildinājumiem un 5 dzēšanām
  1. 20 5
      pkg/fileutils/fileutils_linux.go

+ 20 - 5
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
 }