Skip to content

Commit

Permalink
[common][linux]: improve readlines performance.
Browse files Browse the repository at this point in the history
  • Loading branch information
shirou committed Aug 27, 2023
1 parent 89575bd commit 5435665
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
9 changes: 7 additions & 2 deletions internal/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion internal/common/common_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 4 additions & 1 deletion process/process_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions process/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -862,3 +862,9 @@ func BenchmarkProcessPpid(b *testing.B) {
p.Ppid()
}
}

func BenchmarkProcesses(b *testing.B) {
for i := 0; i < b.N; i++ {
Processes()
}
}

0 comments on commit 5435665

Please sign in to comment.