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