Skip to content

Commit d9f81a9

Browse files
bobrikdiscordianfish
authored andcommitted
Enable oppportunistic fd counting fast path
Existing slow path takes ~725ms of CPU time on my laptopto count 1 million open files. Compare this to just 0.25ms for the baseline, when no extra files are open by a Go program: ``` Open files reported: 7 Gathered metrics in 0.26ms Open files reported: 1000007 Gathered metrics in 724.50ms ``` Adding fastpath from Linux v6.2 makes it fast: ``` Open files reported: 6 Gathered metrics in 0.29ms Open files reported: 1000006 Gathered metrics in 0.31ms ``` This is before taking in account any lock contention effects in the kernel if you try to count files from multiple threads concurrently, which makes the slow path even slower, burning a lot more CPU in the process. See: * torvalds/linux@f1f1f2569901 Signed-off-by: Ivan Babrou <[email protected]>
1 parent 8b6d466 commit d9f81a9

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

proc.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,17 @@ func (p Proc) FileDescriptorTargets() ([]string, error) {
237237
// FileDescriptorsLen returns the number of currently open file descriptors of
238238
// a process.
239239
func (p Proc) FileDescriptorsLen() (int, error) {
240+
// Use fast path if available (Linux v6.2): https://github.com/torvalds/linux/commit/f1f1f2569901
241+
stat, err := os.Stat(p.path("fd"))
242+
if err != nil {
243+
return 0, err
244+
}
245+
246+
size := stat.Size()
247+
if size > 0 {
248+
return int(size), nil
249+
}
250+
240251
fds, err := p.fileDescriptors()
241252
if err != nil {
242253
return 0, err

0 commit comments

Comments
 (0)