Apollo 11.0
自动驾驶开放平台
memory_resource_statistic.cc
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2023 The Apollo Authors. All Rights Reserved.
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 *****************************************************************************/
17
18#include "absl/strings/str_split.h"
19
21
22namespace apollo {
23namespace resource_statistic {
24
25// memory
27 static const std::string system_mem_stat_file = "/proc/meminfo";
28 const int mem_total = 0, available = 2, line_count = 3;
29 const auto stat_lines = GetStatsLines(system_mem_stat_file, line_count);
30 if (stat_lines.size() < line_count) {
31 AERROR << "failed to load contents from " << system_mem_stat_file;
32 return false;
33 }
34 const auto total_memory = GetMemoryValueFromLine(stat_lines[mem_total]);
35 const auto available_memory = GetMemoryValueFromLine(stat_lines[available]);
36 if (available_memory > total_memory) {
37 AERROR << "available memory is larger than total memory";
38 return false;
39 }
40 const auto used_memory = total_memory - available_memory;
41 mem_metric->set_total_mb(total_memory >> 10);
42 mem_metric->set_used_mb(used_memory >> 10);
43 mem_metric->set_available_mb((total_memory - used_memory) >> 10);
44 mem_metric->set_usage(100.f * (static_cast<float>(used_memory) / total_memory));
45 return true;
46}
47
48uint64_t MemoryResourceStatistic::GetMemoryValueFromLine(const std::string& stat_line) {
49 static constexpr int kMemoryValueIdx = 1;
50 const std::vector<std::string> stats = absl::StrSplit(stat_line, ' ', absl::SkipWhitespace());
51 if (stats.size() <= kMemoryValueIdx) {
52 AERROR << "failed to parse memory from line " << stat_line;
53 return 0;
54 }
55 return std::stoll(stats[kMemoryValueIdx]);
56}
57
58} // namespace resource_statistic
59} // namespace apollo
bool GetMemoryMetric(MemoryMetric *mem_metric)
Get memory metric and write it into mem_metric.
#define AERROR
Definition log.h:44
std::vector< std::string > GetStatsLines(const std::string &stat_file, const int line_count)
Get stats lines from file
Definition util.cc:24
class register implement
Definition arena_queue.h:37