Skip to content

Commit db40fde

Browse files
authored
Merge pull request #278 from manugupt1/without-sync
Reduce allocs in ReadUint64 by pre-allocating byte buffer
2 parents 49edf54 + d2d0b18 commit db40fde

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

cgroup1/utils.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,19 @@ func hugePageSizes() ([]string, error) {
131131
}
132132

133133
func readUint(path string) (uint64, error) {
134-
v, err := os.ReadFile(path)
134+
f, err := os.Open(path)
135135
if err != nil {
136136
return 0, err
137137
}
138-
return parseUint(strings.TrimSpace(string(v)), 10, 64)
138+
defer f.Close()
139+
140+
b := make([]byte, 128) // Chose 128 as some files have leading/trailing whitespaces and alignment
141+
n, err := f.Read(b)
142+
if err != nil {
143+
return 0, err
144+
}
145+
146+
return parseUint(strings.TrimSpace(string(b[:n])), 10, 64)
139147
}
140148

141149
func parseUint(s string, base, bitSize int) (uint64, error) {

cgroup1/utils_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Copyright The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package cgroup1
18+
19+
import (
20+
"testing"
21+
)
22+
23+
func BenchmarkReaduint64(b *testing.B) {
24+
b.ReportAllocs()
25+
26+
for i := 0; i < b.N; i++ {
27+
_, err := readUint("/proc/self/loginuid")
28+
if err != nil {
29+
b.Fatal(err)
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)