From 54356650e16162bcb53dff5f078afc2931a0edce Mon Sep 17 00:00:00 2001 From: shirou Date: Sun, 27 Aug 2023 09:03:20 +0000 Subject: [PATCH] [common][linux]: improve readlines performance. --- internal/common/common.go | 9 +++++++-- internal/common/common_linux.go | 3 ++- process/process_linux.go | 5 ++++- process/process_test.go | 6 ++++++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/internal/common/common.go b/internal/common/common.go index 9bfece362..5fcd68b79 100644 --- a/internal/common/common.go +++ b/internal/common/common.go @@ -109,9 +109,14 @@ func ReadFile(filename string) (string, error) { } // ReadLines reads contents from a file and splits them by new lines. -// A convenience wrapper to ReadLinesOffsetN(filename, 0, -1). +// Please do not use this function on Windows platform. func ReadLines(filename string) ([]string, error) { - return ReadLinesOffsetN(filename, 0, -1) + bytes, err := os.ReadFile(filename) + if err != nil { + return []string{""}, err + } + lines := strings.Split(strings.Trim(string(bytes), "\n"), "\n") + return lines, nil } // ReadLinesOffsetN reads contents from file and splits them by new line. diff --git a/internal/common/common_linux.go b/internal/common/common_linux.go index b58edbeb0..770d28e6f 100644 --- a/internal/common/common_linux.go +++ b/internal/common/common_linux.go @@ -89,7 +89,8 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) { } if statFile == "stat" { - for _, line := range lines { + for i := len(lines) - 1; i > 0; i-- { + line := lines[i] if strings.HasPrefix(line, "btime") { f := strings.Fields(line) if len(f) != 2 { diff --git a/process/process_linux.go b/process/process_linux.go index 37cb7ca44..57a28a06f 100644 --- a/process/process_linux.go +++ b/process/process_linux.go @@ -1072,7 +1072,10 @@ func (p *Process) fillFromTIDStatWithContext(ctx context.Context, tid int32) (ui Iowait: iotime / float64(clockTicks), } - bootTime, _ := common.BootTimeWithContext(ctx) + bootTime, err := common.BootTimeWithContext(ctx) + if err != nil { + return 0, 0, nil, 0, 0, 0, nil, err + } t, err := strconv.ParseUint(fields[22], 10, 64) if err != nil { return 0, 0, nil, 0, 0, 0, nil, err diff --git a/process/process_test.go b/process/process_test.go index 9281c93c3..21aba5718 100644 --- a/process/process_test.go +++ b/process/process_test.go @@ -862,3 +862,9 @@ func BenchmarkProcessPpid(b *testing.B) { p.Ppid() } } + +func BenchmarkProcesses(b *testing.B) { + for i := 0; i < b.N; i++ { + Processes() + } +}