Coverage Report

Created: 2026-07-27 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/runtime_profile.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/runtime-profile.cc
19
// and modified by Doris
20
21
#include "runtime/runtime_profile.h"
22
23
#include <gen_cpp/RuntimeProfile_types.h>
24
#include <rapidjson/encodings.h>
25
#include <rapidjson/stringbuffer.h>
26
#include <rapidjson/writer.h>
27
28
#include <algorithm>
29
#include <iomanip>
30
#include <iostream>
31
#include <memory>
32
#include <string>
33
34
#include "common/logging.h"
35
#include "common/object_pool.h"
36
#include "runtime/runtime_profile_counter_tree_node.h"
37
#ifdef BE_TEST
38
#include "common/status.h" // For ErrorCode
39
#endif
40
41
namespace doris {
42
// Thread counters name
43
static const std::string THREAD_VOLUNTARY_CONTEXT_SWITCHES = "VoluntaryContextSwitches";
44
static const std::string THREAD_INVOLUNTARY_CONTEXT_SWITCHES = "InvoluntaryContextSwitches";
45
46
const std::string RuntimeProfile::ROOT_COUNTER;
47
48
3
std::unique_ptr<RuntimeProfile> RuntimeProfile::from_thrift(const TRuntimeProfileTree& node) {
49
3
    if (node.nodes.empty()) {
50
0
        return std::make_unique<RuntimeProfile>("");
51
0
    }
52
3
    TRuntimeProfileNode root_node = node.nodes.front();
53
3
    std::unique_ptr<RuntimeProfile> res = std::make_unique<RuntimeProfile>(root_node.name);
54
3
    res->update(node);
55
3
    return res;
56
3
}
57
58
19
std::unique_ptr<RuntimeProfile> RuntimeProfile::from_proto(const PRuntimeProfileTree& tree) {
59
19
    if (tree.nodes().empty()) {
60
0
        return std::make_unique<RuntimeProfile>("");
61
0
    }
62
63
19
    const PRuntimeProfileNode& root_node = tree.nodes(0);
64
19
    std::unique_ptr<RuntimeProfile> res = std::make_unique<RuntimeProfile>(root_node.name());
65
19
    res->update(tree);
66
19
    return res;
67
19
}
68
69
RuntimeProfile::RuntimeProfile(const std::string& name, bool is_averaged_profile)
70
29.1M
        : _pool(new ObjectPool()),
71
29.1M
          _name(name),
72
29.1M
          _metadata(-1),
73
29.1M
          _timestamp(-1),
74
29.1M
          _is_averaged_profile(is_averaged_profile),
75
29.1M
          _counter_total_time(TUnit::TIME_NS, 0, 3),
76
29.1M
          _local_time_percent(0) {
77
    // TotalTime counter has level3 to disable it from plan profile, because
78
    // it contains its child running time, we use exec time instead.
79
29.1M
    _counter_map["TotalTime"] = &_counter_total_time;
80
29.1M
}
81
82
29.4M
RuntimeProfile::~RuntimeProfile() = default;
83
84
2
bool RuntimeProfile::Counter::operator==(const Counter& other) const {
85
2
    return _value.load(std::memory_order_relaxed) == other._value.load(std::memory_order_relaxed) &&
86
2
           _type == other._type && _level == other._level;
87
2
}
88
89
5.25k
void RuntimeProfile::merge(const RuntimeProfile* other) {
90
5.25k
    DCHECK(other != nullptr);
91
92
    // Merge this level
93
5.25k
    {
94
5.25k
        CounterMap::iterator dst_iter;
95
5.25k
        CounterMap::const_iterator src_iter;
96
5.25k
        std::lock_guard<std::mutex> l(_counter_map_lock);
97
5.25k
        std::lock_guard<std::mutex> m(other->_counter_map_lock);
98
99
22.2k
        for (src_iter = other->_counter_map.begin(); src_iter != other->_counter_map.end();
100
17.0k
             ++src_iter) {
101
17.0k
            dst_iter = _counter_map.find(src_iter->first);
102
103
17.0k
            if (dst_iter == _counter_map.end()) {
104
11.7k
                _counter_map[src_iter->first] = _pool->add(src_iter->second->clone());
105
11.7k
            } else {
106
5.26k
                DCHECK(dst_iter->second->type() == src_iter->second->type());
107
108
5.26k
                if (dst_iter->second->type() == TUnit::DOUBLE_VALUE) {
109
0
                    double new_val =
110
0
                            dst_iter->second->double_value() + src_iter->second->double_value();
111
0
                    dst_iter->second->set(new_val);
112
5.26k
                } else {
113
5.26k
                    dst_iter->second->update(src_iter->second->value());
114
5.26k
                }
115
5.26k
            }
116
17.0k
        }
117
118
5.25k
        ChildCounterMap::const_iterator child_counter_src_itr;
119
120
5.25k
        for (child_counter_src_itr = other->_child_counter_map.begin();
121
10.5k
             child_counter_src_itr != other->_child_counter_map.end(); ++child_counter_src_itr) {
122
5.25k
            _child_counter_map[child_counter_src_itr->first].insert(
123
5.25k
                    child_counter_src_itr->second.begin(), child_counter_src_itr->second.end());
124
5.25k
        }
125
5.25k
    }
126
127
5.25k
    {
128
5.25k
        std::lock_guard<std::mutex> l(_children_lock);
129
5.25k
        std::lock_guard<std::mutex> m(other->_children_lock);
130
131
        // Recursively merge children with matching names
132
5.27k
        for (int i = 0; i < other->_children.size(); ++i) {
133
16
            RuntimeProfile* other_child = other->_children[i].first;
134
16
            ChildMap::iterator j = _child_map.find(other_child->_name);
135
16
            RuntimeProfile* child = nullptr;
136
137
16
            if (j != _child_map.end()) {
138
10
                child = j->second;
139
10
            } else {
140
6
                child = _pool->add(new RuntimeProfile(other_child->_name));
141
6
                child->_local_time_percent = other_child->_local_time_percent;
142
6
                child->_metadata = other_child->_metadata;
143
6
                child->_timestamp = other_child->_timestamp;
144
6
                bool indent_other_child = other->_children[i].second;
145
6
                _child_map[child->_name] = child;
146
6
                _children.push_back(std::make_pair(child, indent_other_child));
147
6
            }
148
149
16
            child->merge(other_child);
150
16
        }
151
5.25k
    }
152
5.25k
}
153
154
16.0k
void RuntimeProfile::update(const TRuntimeProfileTree& thrift_profile) {
155
16.0k
    int idx = 0;
156
16.0k
    update(thrift_profile.nodes, &idx);
157
16.0k
    DCHECK_EQ(idx, thrift_profile.nodes.size());
158
16.0k
}
159
160
25
void RuntimeProfile::update(const PRuntimeProfileTree& proto_profile) {
161
25
    int idx = 0;
162
25
    update(proto_profile.nodes(), &idx);
163
25
    DCHECK_EQ(idx, proto_profile.nodes_size());
164
25
}
165
166
17.2k
void RuntimeProfile::update(const std::vector<TRuntimeProfileNode>& nodes, int* idx) {
167
17.2k
    DCHECK_LT(*idx, nodes.size());
168
17.2k
    const TRuntimeProfileNode& node = nodes[*idx];
169
17.2k
    {
170
17.2k
        std::lock_guard<std::mutex> l(_counter_map_lock);
171
        // update this level
172
17.2k
        std::map<std::string, Counter*>::iterator dst_iter;
173
174
20.3k
        for (int i = 0; i < node.counters.size(); ++i) {
175
3.12k
            const TCounter& tcounter = node.counters[i];
176
3.12k
            CounterMap::iterator j = _counter_map.find(tcounter.name);
177
178
3.12k
            if (j == _counter_map.end()) {
179
2.68k
                _counter_map[tcounter.name] =
180
2.68k
                        _pool->add(new Counter(tcounter.type, tcounter.value));
181
2.68k
            } else {
182
438
                if (j->second->type() != tcounter.type) {
183
0
                    LOG(ERROR) << "Cannot update counters with the same name (" << j->first
184
0
                               << ") but different types.";
185
438
                } else {
186
438
                    j->second->set(tcounter.value);
187
438
                }
188
438
            }
189
3.12k
        }
190
191
17.2k
        ChildCounterMap::const_iterator child_counter_src_itr;
192
193
17.2k
        for (child_counter_src_itr = node.child_counters_map.begin();
194
18.1k
             child_counter_src_itr != node.child_counters_map.end(); ++child_counter_src_itr) {
195
863
            _child_counter_map[child_counter_src_itr->first].insert(
196
863
                    child_counter_src_itr->second.begin(), child_counter_src_itr->second.end());
197
863
        }
198
17.2k
    }
199
200
17.2k
    {
201
17.2k
        std::lock_guard<std::mutex> l(_info_strings_lock);
202
17.2k
        const InfoStrings& info_strings = node.info_strings;
203
17.2k
        for (const std::string& key : node.info_strings_display_order) {
204
            // Look for existing info strings and update in place. If there
205
            // are new strings, add them to the end of the display order.
206
            // TODO: Is nodes.info_strings always a superset of
207
            // _info_strings? If so, can just copy the display order.
208
99
            InfoStrings::const_iterator it = info_strings.find(key);
209
99
            DCHECK(it != info_strings.end());
210
99
            InfoStrings::iterator existing = _info_strings.find(key);
211
212
99
            if (existing == _info_strings.end()) {
213
58
                _info_strings.insert(std::make_pair(key, it->second));
214
58
                _info_strings_display_order.push_back(key);
215
58
            } else {
216
41
                _info_strings[key] = it->second;
217
41
            }
218
99
        }
219
17.2k
    }
220
221
17.2k
    ++*idx;
222
17.2k
    {
223
17.2k
        std::lock_guard<std::mutex> l(_children_lock);
224
225
        // update children with matching names; create new ones if they don't match
226
18.4k
        for (int i = 0; i < node.num_children; ++i) {
227
1.17k
            const TRuntimeProfileNode& tchild = nodes[*idx];
228
1.17k
            ChildMap::iterator j = _child_map.find(tchild.name);
229
1.17k
            RuntimeProfile* child = nullptr;
230
231
1.17k
            if (j != _child_map.end()) {
232
479
                child = j->second;
233
696
            } else {
234
696
                child = _pool->add(new RuntimeProfile(tchild.name));
235
696
                child->_metadata = tchild.metadata;
236
696
                child->_timestamp = tchild.timestamp;
237
696
                _child_map[tchild.name] = child;
238
696
                _children.push_back(std::make_pair(child, tchild.indent));
239
696
            }
240
241
1.17k
            child->update(nodes, idx);
242
1.17k
        }
243
17.2k
    }
244
17.2k
}
245
246
void RuntimeProfile::update(const google::protobuf::RepeatedPtrField<PRuntimeProfileNode>& nodes,
247
37
                            int* idx) {
248
37
    DCHECK_LT(*idx, nodes.size());
249
37
    const PRuntimeProfileNode& node = nodes.Get(*idx);
250
251
37
    {
252
37
        std::lock_guard<std::mutex> l(_counter_map_lock);
253
254
37
        for (const auto& pcounter : node.counters()) {
255
20
            const std::string& name = pcounter.name();
256
20
            auto j = _counter_map.find(name);
257
258
20
            if (j == _counter_map.end()) {
259
14
                _counter_map[name] =
260
14
                        _pool->add(new Counter(unit_to_thrift(pcounter.type()), pcounter.value()));
261
14
            } else {
262
6
                if (unit_to_proto(j->second->type()) != pcounter.type()) {
263
0
                    LOG(ERROR) << "Cannot update counters with the same name (" << name
264
0
                               << ") but different types.";
265
6
                } else {
266
6
                    j->second->set(pcounter.value());
267
6
                }
268
6
            }
269
20
        }
270
271
37
        for (const auto& kv : node.child_counters_map()) {
272
20
            for (const auto& child_name : kv.second.child_counters()) {
273
20
                _child_counter_map[kv.first].insert(child_name);
274
20
            }
275
14
        }
276
37
    }
277
278
37
    {
279
37
        std::lock_guard<std::mutex> l(_info_strings_lock);
280
37
        const auto& info_map = node.info_strings();
281
282
100
        for (const std::string& key : node.info_strings_display_order()) {
283
100
            auto it = info_map.find(key);
284
100
            DCHECK(it != info_map.end());
285
286
100
            auto existing = _info_strings.find(key);
287
100
            if (existing == _info_strings.end()) {
288
99
                _info_strings.insert(std::make_pair(key, it->second));
289
99
                _info_strings_display_order.push_back(key);
290
99
            } else {
291
1
                _info_strings[key] = it->second;
292
1
            }
293
100
        }
294
37
    }
295
296
37
    ++*idx;
297
298
37
    {
299
37
        std::lock_guard<std::mutex> l(_children_lock);
300
49
        for (int i = 0; i < node.num_children(); ++i) {
301
12
            const PRuntimeProfileNode& pchild = nodes.Get(*idx);
302
12
            RuntimeProfile* child = nullptr;
303
304
12
            auto j = _child_map.find(pchild.name());
305
12
            if (j != _child_map.end()) {
306
5
                child = j->second;
307
7
            } else {
308
7
                child = _pool->add(new RuntimeProfile(pchild.name()));
309
7
                child->_metadata = pchild.metadata();
310
7
                child->_timestamp = pchild.timestamp();
311
7
                _child_map[pchild.name()] = child;
312
7
                _children.emplace_back(child, pchild.indent());
313
7
            }
314
315
12
            child->update(nodes, idx);
316
12
        }
317
37
    }
318
37
}
319
320
0
void RuntimeProfile::divide(int n) {
321
0
    DCHECK_GT(n, 0);
322
0
    std::map<std::string, Counter*>::iterator iter;
323
0
    {
324
0
        std::lock_guard<std::mutex> l(_counter_map_lock);
325
326
0
        for (iter = _counter_map.begin(); iter != _counter_map.end(); ++iter) {
327
0
            if (iter->second->type() == TUnit::DOUBLE_VALUE) {
328
0
                iter->second->set(iter->second->double_value() / n);
329
0
            } else {
330
0
                int64_t value = iter->second->_value.load();
331
0
                value = value / n;
332
0
                iter->second->_value.store(value);
333
0
            }
334
0
        }
335
0
    }
336
0
    {
337
0
        std::lock_guard<std::mutex> l(_children_lock);
338
339
0
        for (ChildMap::iterator i = _child_map.begin(); i != _child_map.end(); ++i) {
340
0
            i->second->divide(n);
341
0
        }
342
0
    }
343
0
}
344
345
0
void RuntimeProfile::clear_children() {
346
0
    std::lock_guard<std::mutex> l(_children_lock);
347
0
    _children.clear();
348
0
}
349
350
0
void RuntimeProfile::compute_time_in_profile() {
351
0
    compute_time_in_profile(total_time_counter()->value());
352
0
}
353
354
0
void RuntimeProfile::compute_time_in_profile(int64_t total) {
355
0
    if (total == 0) {
356
0
        return;
357
0
    }
358
359
    // Add all the total times in all the children
360
0
    int64_t total_child_time = 0;
361
0
    std::lock_guard<std::mutex> l(_children_lock);
362
363
0
    for (int i = 0; i < _children.size(); ++i) {
364
0
        total_child_time += _children[i].first->total_time_counter()->value();
365
0
    }
366
367
0
    int64_t local_time = total_time_counter()->value() - total_child_time;
368
    // Counters have some margin, set to 0 if it was negative.
369
0
    local_time = std::max<int64_t>(0L, local_time);
370
0
    _local_time_percent = static_cast<double>(local_time) / static_cast<double>(total);
371
0
    _local_time_percent = std::min(1.0, _local_time_percent) * 100;
372
373
    // Recurse on children
374
0
    for (int i = 0; i < _children.size(); ++i) {
375
0
        _children[i].first->compute_time_in_profile(total);
376
0
    }
377
0
}
378
379
3.94M
RuntimeProfile* RuntimeProfile::create_child(const std::string& name, bool indent, bool prepend) {
380
3.94M
    std::lock_guard<std::mutex> l(_children_lock);
381
3.94M
    DCHECK(_child_map.find(name) == _child_map.end()) << ", name: " << name;
382
3.94M
    RuntimeProfile* child = _pool->add(new RuntimeProfile(name));
383
3.94M
    if (this->is_set_metadata()) {
384
367
        child->set_metadata(this->metadata());
385
367
    }
386
387
3.94M
    if (_children.empty()) {
388
2.28k
        add_child_unlock(child, indent, nullptr);
389
3.93M
    } else {
390
3.93M
        auto* pos = prepend ? _children.begin()->first : nullptr;
391
3.93M
        add_child_unlock(child, indent, pos);
392
3.93M
    }
393
3.94M
    return child;
394
3.94M
}
395
396
RuntimeProfile* RuntimeProfile::get_or_create_child(const std::string& name, bool indent,
397
34
                                                    bool prepend) {
398
34
    std::lock_guard<std::mutex> l(_children_lock);
399
34
    auto it = _child_map.find(name);
400
34
    if (it != _child_map.end()) {
401
31
        return it->second;
402
31
    }
403
404
3
    RuntimeProfile* child = _pool->add(new RuntimeProfile(name));
405
3
    if (this->is_set_metadata()) {
406
0
        child->set_metadata(this->metadata());
407
0
    }
408
3
    auto* location = !_children.empty() && prepend ? _children.front().first : nullptr;
409
3
    add_child_unlock(child, indent, location);
410
3
    return child;
411
34
}
412
413
15.9M
void RuntimeProfile::add_child_unlock(RuntimeProfile* child, bool indent, RuntimeProfile* loc) {
414
15.9M
    DCHECK(child != nullptr);
415
15.9M
    _child_map[child->_name] = child;
416
417
16.2M
    if (loc == nullptr) {
418
16.2M
        _children.push_back(std::make_pair(child, indent));
419
18.4E
    } else {
420
18.4E
        for (ChildVector::iterator it = _children.begin(); it != _children.end(); ++it) {
421
676
            if (it->first == loc) {
422
676
                _children.insert(it, std::make_pair(child, indent));
423
676
                return;
424
676
            }
425
676
        }
426
18.4E
        DCHECK(false) << "Invalid loc";
427
18.4E
    }
428
15.9M
}
429
430
12.1M
void RuntimeProfile::add_child(RuntimeProfile* child, bool indent, RuntimeProfile* loc) {
431
12.1M
    std::lock_guard<std::mutex> l(_children_lock);
432
12.1M
    add_child_unlock(child, indent, loc);
433
12.1M
}
434
435
86.5k
RuntimeProfile* RuntimeProfile::get_child(std::string name) {
436
86.5k
    std::lock_guard<std::mutex> l(_children_lock);
437
86.5k
    auto it = _child_map.find(name);
438
439
86.5k
    if (it == _child_map.end()) {
440
2
        return nullptr;
441
2
    }
442
443
86.5k
    return it->second;
444
86.5k
}
445
446
5
void RuntimeProfile::get_children(std::vector<RuntimeProfile*>* children) const {
447
5
    children->clear();
448
5
    std::lock_guard<std::mutex> l(_children_lock);
449
450
18
    for (ChildMap::const_iterator i = _child_map.begin(); i != _child_map.end(); ++i) {
451
13
        children->push_back(i->second);
452
13
    }
453
5
}
454
455
0
void RuntimeProfile::get_all_children(std::vector<RuntimeProfile*>* children) {
456
0
    std::lock_guard<std::mutex> l(_children_lock);
457
458
0
    for (ChildMap::iterator i = _child_map.begin(); i != _child_map.end(); ++i) {
459
0
        children->push_back(i->second);
460
0
        i->second->get_all_children(children);
461
0
    }
462
0
}
463
464
36.4M
void RuntimeProfile::add_info_string(const std::string& key, const std::string& value) {
465
36.4M
    std::lock_guard<std::mutex> l(_info_strings_lock);
466
36.4M
    InfoStrings::iterator it = _info_strings.find(key);
467
468
36.4M
    if (it == _info_strings.end()) {
469
16.4M
        _info_strings.insert(std::make_pair(key, value));
470
16.4M
        _info_strings_display_order.push_back(key);
471
19.9M
    } else {
472
19.9M
        it->second = value;
473
19.9M
    }
474
36.4M
}
475
476
160
const std::string* RuntimeProfile::get_info_string(const std::string& key) {
477
160
    std::lock_guard<std::mutex> l(_info_strings_lock);
478
160
    InfoStrings::const_iterator it = _info_strings.find(key);
479
480
160
    if (it == _info_strings.end()) {
481
2
        return nullptr;
482
2
    }
483
484
158
    return &it->second;
485
160
}
486
487
RuntimeProfile::HighWaterMarkCounter* RuntimeProfile::AddHighWaterMarkCounter(
488
        const std::string& name, TUnit::type unit, const std::string& parent_counter_name,
489
8.95M
        int64_t level) {
490
8.95M
    DCHECK_EQ(_is_averaged_profile, false);
491
8.95M
    std::lock_guard<std::mutex> l(_counter_map_lock);
492
8.95M
    if (_counter_map.find(name) != _counter_map.end()) {
493
1.01M
        return reinterpret_cast<RuntimeProfile::HighWaterMarkCounter*>(_counter_map[name]);
494
1.01M
    }
495
8.95M
    DCHECK(parent_counter_name == ROOT_COUNTER ||
496
7.94M
           _counter_map.find(parent_counter_name) != _counter_map.end());
497
7.94M
    RuntimeProfile::HighWaterMarkCounter* counter =
498
7.94M
            _pool->add(new RuntimeProfile::HighWaterMarkCounter(unit, level, parent_counter_name));
499
7.94M
    _counter_map[name] = counter;
500
7.94M
    _child_counter_map[parent_counter_name].insert(name);
501
7.94M
    return counter;
502
8.95M
}
503
504
RuntimeProfile::Counter* RuntimeProfile::add_counter(const std::string& name, TUnit::type type,
505
                                                     const std::string& parent_counter_name,
506
170M
                                                     int64_t level) {
507
170M
    std::lock_guard<std::mutex> l(_counter_map_lock);
508
509
170M
    if (_counter_map.find(name) != _counter_map.end()) {
510
26.6M
        return _counter_map[name];
511
26.6M
    }
512
513
    // Parent counter must already exist.
514
170M
    DCHECK(parent_counter_name == ROOT_COUNTER ||
515
144M
           _counter_map.find(parent_counter_name) != _counter_map.end());
516
517
144M
    Counter* counter = _pool->add(new Counter(type, 0, level));
518
144M
    _counter_map[name] = counter;
519
144M
    _child_counter_map[parent_counter_name].insert(name);
520
144M
    return counter;
521
170M
}
522
523
RuntimeProfile::NonZeroCounter* RuntimeProfile::add_nonzero_counter(
524
        const std::string& name, TUnit::type type, const std::string& parent_counter_name,
525
1.86M
        int64_t level) {
526
1.86M
    std::lock_guard<std::mutex> l(_counter_map_lock);
527
1.86M
    if (_counter_map.find(name) != _counter_map.end()) {
528
0
        DCHECK(dynamic_cast<NonZeroCounter*>(_counter_map[name]));
529
0
        return static_cast<NonZeroCounter*>(_counter_map[name]);
530
0
    }
531
532
1.86M
    DCHECK(parent_counter_name == ROOT_COUNTER ||
533
1.86M
           _counter_map.find(parent_counter_name) != _counter_map.end());
534
1.86M
    NonZeroCounter* counter = _pool->add(new NonZeroCounter(type, level, parent_counter_name));
535
1.86M
    _counter_map[name] = counter;
536
1.86M
    _child_counter_map[parent_counter_name].insert(name);
537
1.86M
    return counter;
538
1.86M
}
539
540
RuntimeProfile::DerivedCounter* RuntimeProfile::add_derived_counter(
541
        const std::string& name, TUnit::type type, const DerivedCounterFunction& counter_fn,
542
468k
        const std::string& parent_counter_name) {
543
468k
    std::lock_guard<std::mutex> l(_counter_map_lock);
544
545
468k
    if (_counter_map.find(name) != _counter_map.end()) {
546
0
        return nullptr;
547
0
    }
548
549
468k
    DerivedCounter* counter = _pool->add(new DerivedCounter(type, counter_fn));
550
468k
    _counter_map[name] = counter;
551
468k
    _child_counter_map[parent_counter_name].insert(name);
552
468k
    return counter;
553
468k
}
554
555
void RuntimeProfile::add_description(const std::string& name, const std::string& description,
556
136k
                                     std::string parent_counter_name) {
557
136k
    std::lock_guard<std::mutex> l(_counter_map_lock);
558
559
136k
    if (_counter_map.find(name) != _counter_map.end()) {
560
0
        Counter* counter = _counter_map[name];
561
0
        if (dynamic_cast<DescriptionEntry*>(counter) != nullptr) {
562
            // Do replace instead of update to avoid data race.
563
0
            _counter_map.erase(name);
564
0
        } else {
565
0
            DCHECK(false) << "Counter type mismatch, name: " << name
566
0
                          << ", type: " << counter->type() << ", description: " << description;
567
0
        }
568
0
    }
569
570
    // Parent counter must already exist.
571
136k
    DCHECK(parent_counter_name == ROOT_COUNTER ||
572
136k
           _counter_map.find(parent_counter_name) != _counter_map.end());
573
136k
    DescriptionEntry* counter = _pool->add(new DescriptionEntry(name, description));
574
136k
    _counter_map[name] = counter;
575
136k
    _child_counter_map[parent_counter_name].insert(name);
576
136k
}
577
578
RuntimeProfile::ConditionCounter* RuntimeProfile::add_conditition_counter(
579
        const std::string& name, TUnit::type type, const ConditionCounterFunction& counter_fn,
580
5
        const std::string& parent_counter_name, int64_t level) {
581
5
    std::lock_guard<std::mutex> l(_counter_map_lock);
582
583
5
    if (_counter_map.find(name) != _counter_map.end()) {
584
0
        RuntimeProfile::ConditionCounter* contition_counter =
585
0
                dynamic_cast<ConditionCounter*>(_counter_map[name]);
586
0
        if (contition_counter == nullptr) {
587
0
            throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
588
0
                                   "Failed to add a conditition counter that is duplicate and of a "
589
0
                                   "different type for {}.",
590
0
                                   name);
591
0
        }
592
0
        return contition_counter;
593
0
    }
594
595
5
    ConditionCounter* counter = _pool->add(new ConditionCounter(type, counter_fn, level));
596
5
    _counter_map[name] = counter;
597
5
    _child_counter_map[parent_counter_name].insert(name);
598
5
    return counter;
599
5
}
600
601
355k
RuntimeProfile::Counter* RuntimeProfile::get_counter(const std::string& name) {
602
355k
    std::lock_guard<std::mutex> l(_counter_map_lock);
603
604
355k
    if (_counter_map.find(name) != _counter_map.end()) {
605
69.7k
        return _counter_map[name];
606
69.7k
    }
607
608
285k
    return nullptr;
609
355k
}
610
611
0
void RuntimeProfile::get_counters(const std::string& name, std::vector<Counter*>* counters) {
612
0
    Counter* c = get_counter(name);
613
614
0
    if (c != nullptr) {
615
0
        counters->push_back(c);
616
0
    }
617
618
0
    std::lock_guard<std::mutex> l(_children_lock);
619
620
0
    for (int i = 0; i < _children.size(); ++i) {
621
0
        _children[i].first->get_counters(name, counters);
622
0
    }
623
0
}
624
625
// Print the profile:
626
//  1. Profile Name
627
//  2. Info Strings
628
//  3. Counters
629
//  4. Children
630
void RuntimeProfile::pretty_print(std::ostream* s, const std::string& prefix,
631
141
                                  int64_t profile_level) const {
632
141
    std::ostream& stream = *s;
633
634
    // create copy of _counter_map and _child_counter_map so we don't need to hold lock
635
    // while we call value() on the counters
636
141
    CounterMap counter_map;
637
141
    ChildCounterMap child_counter_map;
638
141
    {
639
141
        std::lock_guard<std::mutex> l(_counter_map_lock);
640
141
        counter_map = _counter_map;
641
141
        child_counter_map = _child_counter_map;
642
141
    }
643
644
141
    std::map<std::string, Counter*>::const_iterator total_time = counter_map.find("TotalTime");
645
141
    DCHECK(total_time != counter_map.end());
646
647
141
    stream.flags(std::ios::fixed);
648
141
    stream << prefix << _name << ":";
649
650
141
    if (total_time->second->value() != 0) {
651
0
        stream << "(Active: "
652
0
               << PrettyPrinter::print(total_time->second->value(), total_time->second->type())
653
0
               << ", non-child: " << std::setprecision(2) << _local_time_percent << "%)";
654
0
    }
655
656
141
    stream << std::endl;
657
658
141
    {
659
141
        std::lock_guard<std::mutex> l(_info_strings_lock);
660
141
        for (const std::string& key : _info_strings_display_order) {
661
1
            stream << prefix << "   - " << key << ": " << _info_strings.find(key)->second
662
1
                   << std::endl;
663
1
        }
664
141
    }
665
666
    // Build counter tree and prune by profile_level before printing
667
141
    RuntimeProfileCounterTreeNode counter_tree =
668
141
            RuntimeProfileCounterTreeNode::from_map(counter_map, child_counter_map, ROOT_COUNTER);
669
141
    counter_tree = RuntimeProfileCounterTreeNode::prune_the_tree(counter_tree, profile_level);
670
141
    counter_tree.pretty_print(s, prefix);
671
672
    // create copy of _children so we don't need to hold lock while we call
673
    // pretty_print() on the children
674
141
    ChildVector children;
675
141
    {
676
141
        std::lock_guard<std::mutex> l(_children_lock);
677
141
        children = _children;
678
141
    }
679
680
227
    for (int i = 0; i < children.size(); ++i) {
681
86
        RuntimeProfile* profile = children[i].first;
682
86
        bool indent = children[i].second;
683
86
        profile->pretty_print(s, prefix + (indent ? "  " : ""));
684
86
    }
685
141
}
686
687
26.0k
void RuntimeProfile::to_thrift(TRuntimeProfileTree* tree, int64_t profile_level) {
688
26.0k
    tree->nodes.clear();
689
26.0k
    to_thrift(&tree->nodes, profile_level);
690
26.0k
}
691
692
149k
void RuntimeProfile::to_thrift(std::vector<TRuntimeProfileNode>* nodes, int64_t profile_level) {
693
149k
    size_t index = nodes->size();
694
149k
    nodes->push_back(TRuntimeProfileNode());
695
149k
    TRuntimeProfileNode& node = (*nodes)[index];
696
149k
    node.name = _name;
697
149k
    node.metadata = _metadata;
698
149k
    node.timestamp = _timestamp;
699
149k
    node.indent = true;
700
701
149k
    {
702
149k
        std::lock_guard<std::mutex> l(_counter_map_lock);
703
149k
        RuntimeProfileCounterTreeNode conter_tree = RuntimeProfileCounterTreeNode::from_map(
704
149k
                _counter_map, _child_counter_map, ROOT_COUNTER);
705
149k
        conter_tree = RuntimeProfileCounterTreeNode::prune_the_tree(conter_tree, profile_level);
706
149k
        conter_tree.to_thrift(node.counters, node.child_counters_map);
707
149k
    }
708
709
149k
    {
710
149k
        std::lock_guard<std::mutex> l(_info_strings_lock);
711
149k
        node.info_strings = _info_strings;
712
149k
        node.info_strings_display_order = _info_strings_display_order;
713
149k
    }
714
715
149k
    ChildVector children;
716
149k
    {
717
        // _children may be modified during to_thrift(),
718
        // so we have to lock and copy _children to avoid race condition
719
149k
        std::lock_guard<std::mutex> l(_children_lock);
720
149k
        children = _children;
721
149k
    }
722
149k
    node.num_children = cast_set<int32_t>(children.size());
723
149k
    nodes->reserve(nodes->size() + children.size());
724
725
273k
    for (int i = 0; i < children.size(); ++i) {
726
123k
        size_t child_idx = nodes->size();
727
123k
        children[i].first->to_thrift(nodes, profile_level);
728
        // fix up indentation flag
729
123k
        (*nodes)[child_idx].indent = children[i].second;
730
123k
    }
731
149k
}
732
733
21
void RuntimeProfile::to_proto(PRuntimeProfileTree* tree, int64_t profile_level) {
734
21
    tree->clear_nodes();
735
21
    to_proto(tree->mutable_nodes(), profile_level);
736
21
}
737
738
void RuntimeProfile::to_proto(google::protobuf::RepeatedPtrField<PRuntimeProfileNode>* nodes,
739
27
                              int64_t profile_level) {
740
27
    PRuntimeProfileNode* node = nodes->Add(); // allocate new node
741
27
    node->set_name(_name);
742
27
    node->set_metadata(_metadata);
743
27
    node->set_timestamp(_timestamp);
744
27
    node->set_indent(true);
745
746
27
    {
747
27
        std::lock_guard<std::mutex> l(_counter_map_lock);
748
27
        RuntimeProfileCounterTreeNode counter_tree = RuntimeProfileCounterTreeNode::from_map(
749
27
                _counter_map, _child_counter_map, ROOT_COUNTER);
750
27
        counter_tree = RuntimeProfileCounterTreeNode::prune_the_tree(counter_tree, profile_level);
751
27
        counter_tree.to_proto(node->mutable_counters(), node->mutable_child_counters_map());
752
27
    }
753
754
27
    {
755
27
        std::lock_guard<std::mutex> l(_info_strings_lock);
756
27
        auto* info_map = node->mutable_info_strings();
757
99
        for (const auto& kv : _info_strings) {
758
99
            (*info_map)[kv.first] = kv.second;
759
99
        }
760
99
        for (const auto& key : _info_strings_display_order) {
761
99
            node->add_info_strings_display_order(key);
762
99
        }
763
27
    }
764
765
27
    ChildVector children;
766
27
    {
767
27
        std::lock_guard<std::mutex> l(_children_lock);
768
27
        children = _children;
769
27
    }
770
771
27
    node->set_num_children(cast_set<int32_t>(children.size()));
772
773
27
    for (const auto& child : children) {
774
6
        int child_index = cast_set<int>(nodes->size()); // capture index for indent correction
775
6
        child.first->to_proto(nodes, profile_level);
776
6
        (*nodes)[child_index].set_indent(child.second);
777
6
    }
778
27
}
779
780
int64_t RuntimeProfile::units_per_second(const RuntimeProfile::Counter* total_counter,
781
6.42k
                                         const RuntimeProfile::Counter* timer) {
782
6.42k
    DCHECK(total_counter->type() == TUnit::BYTES || total_counter->type() == TUnit::UNIT);
783
6.42k
    DCHECK(timer->type() == TUnit::TIME_NS);
784
785
6.42k
    if (timer->value() == 0) {
786
6.42k
        return 0;
787
6.42k
    }
788
789
3
    double secs = static_cast<double>(timer->value()) / 1000.0 / 1000.0 / 1000.0;
790
3
    return int64_t(static_cast<double>(total_counter->value()) / secs);
791
6.42k
}
792
793
0
int64_t RuntimeProfile::counter_sum(const std::vector<Counter*>* counters) {
794
0
    int64_t value = 0;
795
796
0
    for (int i = 0; i < counters->size(); ++i) {
797
0
        value += (*counters)[i]->value();
798
0
    }
799
800
0
    return value;
801
0
}
802
803
void RuntimeProfile::print_child_counters(const std::string& prefix,
804
                                          const std::string& counter_name,
805
                                          const CounterMap& counter_map,
806
                                          const ChildCounterMap& child_counter_map,
807
0
                                          std::ostream* s) {
808
0
    auto itr = child_counter_map.find(counter_name);
809
810
0
    if (itr != child_counter_map.end()) {
811
0
        const std::set<std::string>& child_counters = itr->second;
812
0
        for (const std::string& child_counter : child_counters) {
813
0
            auto iter = counter_map.find(child_counter);
814
            DCHECK(iter != counter_map.end());
815
0
            iter->second->pretty_print(s, prefix, iter->first);
816
0
            RuntimeProfile::print_child_counters(prefix + "  ", child_counter, counter_map,
817
0
                                                 child_counter_map, s);
818
0
        }
819
0
    }
820
0
}
821
822
} // namespace doris