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>
(cherry picked from commit eaa9494b71
)
Resolved conflicts:
pkg/fileutils/fileutils_linux.go
Signed-off-by: Bjorn Neergaard <bjorn.neergaard@docker.com>
This commit is contained in:
parent
55c8d163d7
commit
6c4adc0037
1 changed files with 20 additions and 5 deletions
|
@ -2,6 +2,7 @@ package fileutils
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
@ -10,10 +11,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 {
|
||||
logrus.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 {
|
||||
logrus.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 {
|
||||
logrus.WithError(err).Error("Error listing file descriptors")
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return fdCount
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue