• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 gRPC 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 #include "test/core/memory_usage/memstats.h"
16 
17 #include <unistd.h>
18 
19 #include <fstream>
20 #include <string>
21 
22 #include "absl/log/check.h"
23 #include "absl/strings/str_cat.h"
24 
GetMemUsage(absl::optional<int> pid)25 long GetMemUsage(absl::optional<int> pid) {
26   // Default is getting memory usage for self (calling process)
27   std::string path = "/proc/self/stat";
28   if (pid != absl::nullopt) {
29     path = absl::StrCat("/proc/", pid.value(), "/stat");
30   }
31   std::ifstream stat_stream(path, std::ios_base::in);
32 
33   double resident_set = 0.0;
34   // Temporary variables for irrelevant leading entries in stats
35   std::string temp_pid, comm, state, ppid, pgrp, session, tty_nr;
36   std::string tpgid, flags, minflt, cminflt, majflt, cmajflt;
37   std::string utime, stime, cutime, cstime, priority, nice;
38   std::string O, itrealvalue, starttime, vsize;
39 
40   // Get rss to find memory usage
41   long rss;
42   stat_stream >> temp_pid >> comm >> state >> ppid >> pgrp >> session >>
43       tty_nr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >>
44       utime >> stime >> cutime >> cstime >> priority >> nice >> O >>
45       itrealvalue >> starttime >> vsize >> rss;
46   stat_stream.close();
47 
48   // pid does not connect to an existing process
49   CHECK(!state.empty());
50 
51   // Calculations in case x86-64 is configured to use 2MB pages
52   long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024;
53   resident_set = rss * page_size_kb;
54   // Memory in KB
55   return resident_set;
56 }
57