1 /*
2  * Copyright (C) 2021 The Android Open Source Project
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 #ifndef ART_LIBARTBASE_BASE_STATS_INL_H_
18 #define ART_LIBARTBASE_BASE_STATS_INL_H_
19 
20 #include <iomanip>
21 #include <map>
22 
23 #include "base/stats.h"
24 #include "base/indenter.h"
25 
26 namespace art {
DumpSizes(VariableIndentationOutputStream & os,std::string_view name)27   void Stats::DumpSizes(VariableIndentationOutputStream& os, std::string_view name) const {
28     Dump(os, name, Value(), 1000.0, "KB");
29   }
30 
Dump(VariableIndentationOutputStream & os,std::string_view name,double total,double unit_size,const char * unit)31   void Stats::Dump(VariableIndentationOutputStream& os,
32                    std::string_view name,
33                    double total,
34                    double unit_size,
35                    const char* unit) const {
36     double percent = total > 0 ? 100.0 * Value() / total : 0;
37     const size_t name_width = 52 - os.GetIndentation();
38     if (name.length() > name_width) {
39       // Handle very long names by printing them on their own line.
40       os.Stream() << name << " \\\n";
41       name = "";
42     }
43     os.Stream()
44         << std::setw(name_width) << std::left << name << " "
45         << std::setw(6) << std::right << Count() << " "
46         << std::setw(10) << std::fixed << std::setprecision(3) << Value() / unit_size << unit << " "
47         << std::setw(6) << std::fixed << std::setprecision(1) << percent << "%\n";
48 
49     // Sort all children by largest value first, then by name.
50     std::map<std::pair<double, std::string_view>, const Stats&> sorted_children;
51     for (const auto& it : Children()) {
52       sorted_children.emplace(std::make_pair(-it.second.Value(), it.first), it.second);
53     }
54 
55     // Add "other" row to represent any amount not account for by the children.
56     Stats other;
57     other.AddBytes(Value() - SumChildrenValues(), Count());
58     if (other.Value() != 0.0 && !Children().empty()) {
59       sorted_children.emplace(std::make_pair(-other.Value(), "(other)"), other);
60     }
61 
62     // Print the data.
63     ScopedIndentation indent1(&os);
64     for (const auto& it : sorted_children) {
65       it.second.Dump(os, it.first.second, total, unit_size, unit);
66     }
67   }
68 }  // namespace art
69 
70 #endif  // ART_LIBARTBASE_BASE_STATS_INL_H_
71