github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/benchmarks/tools/meminfo.go (about) 1 // Copyright 2020 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package tools 16 17 import ( 18 "fmt" 19 "regexp" 20 "strconv" 21 "testing" 22 ) 23 24 // Meminfo wraps measurements of MemAvailable using /proc/meminfo. 25 type Meminfo struct { 26 } 27 28 // MakeCmd returns a command for checking meminfo. 29 func (*Meminfo) MakeCmd() (string, []string) { 30 return "cat", []string{"/proc/meminfo"} 31 } 32 33 // Report takes two reads of meminfo, parses them, and reports the difference 34 // divided by b.N. 35 func (*Meminfo) Report(b *testing.B, before, after string) { 36 b.Helper() 37 38 beforeVal, err := parseMemAvailable(before) 39 if err != nil { 40 b.Fatalf("could not parse before value %s: %v", before, err) 41 } 42 43 afterVal, err := parseMemAvailable(after) 44 if err != nil { 45 b.Fatalf("could not parse before value %s: %v", before, err) 46 } 47 val := 1024 * ((beforeVal - afterVal) / float64(b.N)) 48 ReportCustomMetric(b, val, "average_container_size" /*metric name*/, "bytes" /*units*/) 49 } 50 51 var memInfoRE = regexp.MustCompile(`MemAvailable:\s*(\d+)\skB\n`) 52 53 // parseMemAvailable grabs the MemAvailable number from /proc/meminfo. 54 func parseMemAvailable(data string) (float64, error) { 55 match := memInfoRE.FindStringSubmatch(data) 56 if len(match) < 2 { 57 return 0, fmt.Errorf("couldn't find MemAvailable in %s", data) 58 } 59 return strconv.ParseFloat(match[1], 64) 60 }