Coverage Report

Created: 2026-08-07 13:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/runtime/runtime_profile.h
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.h
19
// and modified by Doris
20
21
#pragma once
22
23
#include <gen_cpp/Metrics_types.h>
24
#include <gen_cpp/RuntimeProfile_types.h>
25
#include <gen_cpp/runtime_profile.pb.h>
26
#include <glog/logging.h>
27
#include <stdint.h>
28
29
#include <algorithm>
30
#include <atomic>
31
#include <cstdint>
32
#include <functional>
33
#include <iostream>
34
#include <map>
35
#include <memory>
36
#include <mutex>
37
#include <set>
38
#include <string>
39
#include <utility>
40
#include <vector>
41
42
#include "common/compiler_util.h" // IWYU pragma: keep
43
#include "common/logging.h"
44
#include "core/binary_cast.hpp"
45
#include "util/pretty_printer.h"
46
#include "util/stopwatch.hpp"
47
48
namespace doris {
49
#include "common/compile_check_begin.h"
50
class TRuntimeProfileNode;
51
class TRuntimeProfileTree;
52
class RuntimeProfileCounterTreeNode;
53
54
// Some macro magic to generate unique ids using __COUNTER__
55
6.49M
#define CONCAT_IMPL(x, y) x##y
56
6.49M
#define MACRO_CONCAT(x, y) CONCAT_IMPL(x, y)
57
58
#define ADD_LABEL_COUNTER(profile, name) (profile)->add_counter(name, TUnit::NONE)
59
#define ADD_LABEL_COUNTER_WITH_LEVEL(profile, name, level) \
60
    (profile)->add_counter_with_level(name, TUnit::NONE, level)
61
2.23M
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
62
#define ADD_COUNTER_WITH_LEVEL(profile, name, type, level) \
63
462k
    (profile)->add_counter_with_level(name, type, level)
64
582k
#define ADD_TIMER(profile, name) (profile)->add_counter(name, TUnit::TIME_NS)
65
#define ADD_TIMER_WITH_LEVEL(profile, name, level) \
66
510k
    (profile)->add_counter_with_level(name, TUnit::TIME_NS, level)
67
28
#define ADD_CHILD_COUNTER(profile, name, type, parent) (profile)->add_counter(name, type, parent)
68
#define ADD_CHILD_COUNTER_WITH_LEVEL(profile, name, type, parent, level) \
69
28.4k
    (profile)->add_counter(name, type, parent, level)
70
606
#define ADD_CHILD_TIMER(profile, name, parent) (profile)->add_counter(name, TUnit::TIME_NS, parent)
71
#define ADD_CHILD_TIMER_WITH_LEVEL(profile, name, parent, level) \
72
15.1k
    (profile)->add_counter(name, TUnit::TIME_NS, parent, level)
73
2.03M
#define SCOPED_TIMER(c) ScopedTimer<MonotonicStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
74
#define SCOPED_TIMER_ATOMIC(c) \
75
    ScopedTimer<MonotonicStopWatch, std::atomic_bool> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
76
#define SCOPED_CPU_TIMER(c) \
77
106
    ScopedTimer<ThreadCpuStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
78
#define CANCEL_SAFE_SCOPED_TIMER(c, is_cancelled) \
79
    ScopedTimer<MonotonicStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c, is_cancelled)
80
#define SCOPED_RAW_TIMER(c)                                                                  \
81
4.45M
    doris::ScopedRawTimer<doris::MonotonicStopWatch, int64_t> MACRO_CONCAT(SCOPED_RAW_TIMER, \
82
4.45M
                                                                           __COUNTER__)(c)
83
#define SCOPED_ATOMIC_TIMER(c)                                                                 \
84
0
    ScopedRawTimer<MonotonicStopWatch, std::atomic<int64_t>> MACRO_CONCAT(SCOPED_ATOMIC_TIMER, \
85
0
                                                                          __COUNTER__)(c)
86
162k
#define COUNTER_UPDATE(c, v) (c)->update(v)
87
330k
#define COUNTER_SET(c, v) (c)->set(v)
88
89
class ObjectPool;
90
91
// Runtime profile is a group of profiling counters.  It supports adding named counters
92
// and being able to serialize and deserialize them.
93
// The profiles support a tree structure to form a hierarchy of counters.
94
// Runtime profiles supports measuring wall clock rate based counters.  There is a
95
// single thread per process that will convert an amount (i.e. bytes) counter to a
96
// corresponding rate based counter.  This thread wakes up at fixed intervals and updates
97
// all of the rate counters.
98
// Thread-safe.
99
class RuntimeProfile {
100
public:
101
    static std::unique_ptr<RuntimeProfile> from_thrift(const TRuntimeProfileTree& node);
102
103
    static std::unique_ptr<RuntimeProfile> from_proto(const PRuntimeProfileTree& tree);
104
105
14
    static PProfileUnit unit_to_proto(const TUnit::type& type) {
106
14
        switch (type) {
107
11
        case TUnit::UNIT: {
108
11
            return PProfileUnit::UNIT;
109
0
        }
110
0
        case TUnit::UNIT_PER_SECOND: {
111
0
            return PProfileUnit::UNIT_PER_SECOND;
112
0
        }
113
0
        case TUnit::CPU_TICKS: {
114
0
            return PProfileUnit::CPU_TICKS;
115
0
        }
116
3
        case TUnit::BYTES: {
117
3
            return PProfileUnit::BYTES;
118
0
        }
119
0
        case TUnit::BYTES_PER_SECOND: {
120
0
            return PProfileUnit::BYTES_PER_SECOND;
121
0
        }
122
0
        case TUnit::TIME_NS: {
123
0
            return PProfileUnit::TIME_NS;
124
0
        }
125
0
        case TUnit::DOUBLE_VALUE: {
126
0
            return PProfileUnit::DOUBLE_VALUE;
127
0
        }
128
0
        case TUnit::NONE: {
129
0
            return PProfileUnit::NONE;
130
0
        }
131
0
        case TUnit::TIME_MS: {
132
0
            return PProfileUnit::TIME_MS;
133
0
        }
134
0
        case TUnit::TIME_S: {
135
0
            return PProfileUnit::TIME_S;
136
0
        }
137
0
        default: {
138
0
            DCHECK(false);
139
0
            return PProfileUnit::NONE;
140
0
        }
141
14
        }
142
14
    }
143
144
14
    static TUnit::type unit_to_thrift(const PProfileUnit& unit) {
145
14
        switch (unit) {
146
12
        case PProfileUnit::UNIT: {
147
12
            return TUnit::UNIT;
148
0
        }
149
0
        case PProfileUnit::UNIT_PER_SECOND: {
150
0
            return TUnit::UNIT_PER_SECOND;
151
0
        }
152
0
        case PProfileUnit::CPU_TICKS: {
153
0
            return TUnit::CPU_TICKS;
154
0
        }
155
2
        case PProfileUnit::BYTES: {
156
2
            return TUnit::BYTES;
157
0
        }
158
0
        case PProfileUnit::BYTES_PER_SECOND: {
159
0
            return TUnit::BYTES_PER_SECOND;
160
0
        }
161
0
        case PProfileUnit::TIME_NS: {
162
0
            return TUnit::TIME_NS;
163
0
        }
164
0
        case PProfileUnit::DOUBLE_VALUE: {
165
0
            return TUnit::DOUBLE_VALUE;
166
0
        }
167
0
        case PProfileUnit::NONE: {
168
0
            return TUnit::NONE;
169
0
        }
170
0
        case PProfileUnit::TIME_MS: {
171
0
            return TUnit::TIME_MS;
172
0
        }
173
0
        case PProfileUnit::TIME_S: {
174
0
            return TUnit::TIME_S;
175
0
        }
176
0
        default: {
177
0
            DCHECK(false);
178
0
            return TUnit::NONE;
179
0
        }
180
14
        }
181
14
    }
182
183
    // The root counter name for all top level counters.
184
    static const std::string ROOT_COUNTER;
185
    class Counter {
186
    public:
187
        Counter(TUnit::type type, int64_t value = 0, int64_t level = 3)
188
5.61M
                : _value(value), _type(type), _level(level) {}
189
5.61M
        virtual ~Counter() = default;
190
191
8
        virtual Counter* clone() const { return new Counter(type(), value(), _level); }
192
193
3.18M
        virtual void update(int64_t delta) { _value.fetch_add(delta, std::memory_order_relaxed); }
194
195
0
        void bit_or(int64_t delta) { _value.fetch_or(delta, std::memory_order_relaxed); }
196
197
379k
        virtual void set(int64_t value) { _value.store(value, std::memory_order_relaxed); }
198
199
0
        virtual void set(double value) {
200
0
            DCHECK_EQ(sizeof(value), sizeof(int64_t));
201
0
            _value.store(binary_cast<double, int64_t>(value), std::memory_order_relaxed);
202
0
        }
203
204
366k
        virtual int64_t value() const { return _value.load(std::memory_order_relaxed); }
205
206
0
        virtual double double_value() const {
207
0
            return binary_cast<int64_t, double>(_value.load(std::memory_order_relaxed));
208
0
        }
209
210
50.8k
        virtual TCounter to_thrift(const std::string& name) const {
211
50.8k
            TCounter counter;
212
50.8k
            counter.name = name;
213
50.8k
            counter.value = this->value();
214
50.8k
            counter.type = this->type();
215
50.8k
            counter.__set_level(this->_level);
216
50.8k
            return counter;
217
50.8k
        }
218
219
8
        virtual PProfileCounter to_proto(const std::string& name) const {
220
8
            PProfileCounter counter;
221
8
            counter.set_name(name);
222
8
            counter.set_value(this->value());
223
8
            counter.set_type(unit_to_proto(this->type()));
224
8
            counter.set_level(this->value());
225
8
            return counter;
226
8
        }
227
228
        virtual void pretty_print(std::ostream* s, const std::string& prefix,
229
315
                                  const std::string& name) const {
230
315
            std::ostream& stream = *s;
231
315
            stream << prefix << "   - " << name << ": "
232
315
                   << PrettyPrinter::print(_value.load(std::memory_order_relaxed), type())
233
315
                   << std::endl;
234
315
        }
235
236
2.08M
        TUnit::type type() const { return _type; }
237
238
51.1k
        virtual int64_t level() const { return _level; }
239
240
3
        void set_level(int64_t level) { _level = level; }
241
242
        bool operator==(const Counter& other) const;
243
244
    private:
245
        friend class RuntimeProfile;
246
        friend class RuntimeProfileCounterTreeNode;
247
248
        std::atomic<int64_t> _value;
249
        TUnit::type _type;
250
        int64_t _level;
251
    };
252
253
    /// A counter that keeps track of the highest value seen (reporting that
254
    /// as value()) and the current value.
255
    class HighWaterMarkCounter : public Counter {
256
    public:
257
        HighWaterMarkCounter(TUnit::type unit, int64_t level, const std::string& parent_name,
258
                             int64_t value = 0, int64_t current_value = 0)
259
121k
                : Counter(unit, value, level),
260
121k
                  current_value_(current_value),
261
121k
                  _parent_name(parent_name) {}
262
263
0
        virtual Counter* clone() const override {
264
0
            return new HighWaterMarkCounter(type(), level(), parent_name(), value(),
265
0
                                            current_value());
266
0
        }
267
268
3.84k
        void add(int64_t delta) {
269
3.84k
            current_value_.fetch_add(delta, std::memory_order_relaxed);
270
3.84k
            if (delta > 0) {
271
1.94k
                UpdateMax(current_value_);
272
1.94k
            }
273
3.84k
        }
274
3.80k
        virtual void update(int64_t delta) override { add(delta); }
275
276
4
        TCounter to_thrift(const std::string& name) const override {
277
4
            TCounter counter;
278
4
            counter.name = std::move(name);
279
4
            counter.value = current_value();
280
4
            counter.type = type();
281
4
            counter.__set_level(level());
282
4
            return counter;
283
4
        }
284
285
0
        PProfileCounter to_proto(const std::string& name) const override {
286
0
            PProfileCounter counter;
287
0
            counter.set_name(name);
288
0
            counter.set_value(current_value());
289
0
            counter.set_type(unit_to_proto(this->type()));
290
0
            counter.set_level(this->value());
291
0
            return counter;
292
0
        }
293
294
4
        TCounter to_thrift_peak(std::string name) {
295
4
            TCounter counter;
296
4
            counter.name = std::move(name);
297
4
            counter.value = value();
298
4
            counter.type = type();
299
4
            counter.__set_level(level());
300
4
            return counter;
301
4
        }
302
303
0
        PProfileCounter to_proto_peak(const std::string& name) const {
304
0
            return Counter::to_proto(name);
305
0
        }
306
307
        virtual void pretty_print(std::ostream* s, const std::string& prefix,
308
82
                                  const std::string& name) const override {
309
82
            std::ostream& stream = *s;
310
82
            stream << prefix << "   - " << name
311
82
                   << " Current: " << PrettyPrinter::print(current_value(), type()) << " (Peak: "
312
82
                   << PrettyPrinter::print(_value.load(std::memory_order_relaxed), type()) << ")"
313
82
                   << std::endl;
314
82
        }
315
316
        /// Tries to increase the current value by delta. If current_value() + delta
317
        /// exceeds max, return false and current_value is not changed.
318
0
        bool try_add(int64_t delta, int64_t max) {
319
0
            while (true) {
320
0
                int64_t old_val = current_value_.load(std::memory_order_relaxed);
321
0
                int64_t new_val = old_val + delta;
322
0
                if (UNLIKELY(new_val > max)) return false;
323
0
                if (LIKELY(current_value_.compare_exchange_weak(old_val, new_val,
324
0
                                                                std::memory_order_relaxed))) {
325
0
                    UpdateMax(new_val);
326
0
                    return true;
327
0
                }
328
0
            }
329
0
        }
330
331
96.4k
        void set(int64_t v) override {
332
96.4k
            current_value_.store(v, std::memory_order_relaxed);
333
96.4k
            UpdateMax(v);
334
96.4k
        }
335
336
86
        int64_t current_value() const { return current_value_.load(std::memory_order_relaxed); }
337
338
4
        std::string parent_name() const { return _parent_name; }
339
340
    private:
341
        /// Set '_value' to 'v' if 'v' is larger than '_value'. The entire operation is
342
        /// atomic.
343
98.4k
        void UpdateMax(int64_t v) {
344
98.4k
            while (true) {
345
98.4k
                int64_t old_max = _value.load(std::memory_order_relaxed);
346
98.4k
                int64_t new_max = std::max(old_max, v);
347
98.4k
                if (new_max == old_max) {
348
1.77k
                    break; // Avoid atomic update.
349
1.77k
                }
350
96.6k
                if (LIKELY(_value.compare_exchange_weak(old_max, new_max,
351
96.6k
                                                        std::memory_order_relaxed))) {
352
96.6k
                    break;
353
96.6k
                }
354
96.6k
            }
355
98.4k
        }
356
357
        /// The current value of the counter. _value in the super class represents
358
        /// the high water mark.
359
        std::atomic<int64_t> current_value_;
360
361
        const std::string _parent_name;
362
    };
363
364
    using DerivedCounterFunction = std::function<int64_t()>;
365
366
    // A DerivedCounter also has a name and type, but the value is computed.
367
    // Do not call Set() and Update().
368
    class DerivedCounter : public Counter {
369
    public:
370
        DerivedCounter(TUnit::type type, const DerivedCounterFunction& counter_fn,
371
                       int64_t value = 0, int64_t level = 1)
372
8
                : Counter(type, value, level), _counter_fn(counter_fn) {}
373
374
0
        virtual Counter* clone() const override {
375
0
            return new DerivedCounter(type(), _counter_fn, value(), level());
376
0
        }
377
378
3
        int64_t value() const override { return _counter_fn(); }
379
380
    private:
381
        DerivedCounterFunction _counter_fn;
382
    };
383
384
    using ConditionCounterFunction = std::function<bool(int64_t, int64_t)>;
385
386
    // ConditionCounter is a specialized counter that only updates its value when a specific condition is met.
387
    // It uses a condition function (condition_func) to determine when the counter's value should be updated.
388
    // This type of counter is particularly useful for tracking maximum values, minimum values, or other metrics
389
    // that should only be updated when they meet certain criteria.
390
    // For example, it can be used to record the maximum value of a specific metric during query execution,
391
    // or to update the counter only when a new value exceeds some threshold.
392
    class ConditionCounter : public Counter {
393
    public:
394
        ConditionCounter(TUnit::type type, const ConditionCounterFunction& condition_func,
395
                         int64_t level = 2, int64_t condition = 0, int64_t value = 0)
396
5
                : Counter(type, value, level),
397
5
                  _condition(condition),
398
5
                  _stored_value(value),
399
5
                  _condition_func(condition_func) {}
400
401
0
        Counter* clone() const override {
402
0
            std::lock_guard<std::mutex> l(_mutex);
403
0
            return new ConditionCounter(type(), _condition_func, _condition, value(), level());
404
0
        }
405
406
7
        int64_t value() const override {
407
7
            std::lock_guard<std::mutex> l(_mutex);
408
7
            return _stored_value;
409
7
        }
410
411
7
        void conditional_update(int64_t c, int64_t v) {
412
7
            std::lock_guard<std::mutex> l(_mutex);
413
7
            if (_condition_func(_condition, c)) {
414
4
                _stored_value = v;
415
4
                _condition = c;
416
4
            }
417
7
        }
418
419
    private:
420
        mutable std::mutex _mutex;
421
        int64_t _condition;
422
        int64_t _stored_value;
423
        ConditionCounterFunction _condition_func;
424
    };
425
426
    // NonZeroCounter will not be converted to Thrift if the value is 0.
427
    class NonZeroCounter : public Counter {
428
    public:
429
        NonZeroCounter(TUnit::type type, int64_t level, const std::string& parent_name,
430
                       int64_t value = 0)
431
34
                : Counter(type, value, level), _parent_name(parent_name) {}
432
433
0
        virtual Counter* clone() const override {
434
0
            return new NonZeroCounter(type(), level(), parent_name(), value());
435
0
        }
436
437
1
        std::string parent_name() const { return _parent_name; }
438
439
    private:
440
        const std::string _parent_name;
441
    };
442
443
    class DescriptionEntry : public Counter {
444
    public:
445
        DescriptionEntry(const std::string& name, const std::string& description)
446
72.0k
                : Counter(TUnit::NONE, 0, 2), _description(description), _name(name) {}
447
448
0
        virtual Counter* clone() const override {
449
0
            return new DescriptionEntry(_name, _description);
450
0
        }
451
452
0
        void set(int64_t value) override {
453
            // Do nothing
454
0
        }
455
0
        void set(double value) override {
456
            // Do nothing
457
0
        }
458
0
        void update(int64_t delta) override {
459
            // Do nothing
460
0
        }
461
462
1
        TCounter to_thrift(const std::string& name) const override {
463
1
            TCounter counter;
464
1
            counter.name = name;
465
1
            counter.__set_level(2);
466
1
            counter.__set_description(_description);
467
1
            return counter;
468
1
        }
469
470
0
        PProfileCounter to_proto(const std::string& name) const override {
471
0
            PProfileCounter counter;
472
0
            counter.set_name(name);
473
0
            counter.set_level(2);
474
0
            counter.set_description(_description);
475
0
            return counter;
476
0
        }
477
478
    private:
479
        const std::string _description;
480
        const std::string _name;
481
    };
482
483
    // Create a runtime profile object with 'name'.
484
    RuntimeProfile(const std::string& name, bool is_averaged_profile = false);
485
486
    ~RuntimeProfile();
487
488
    // Adds a child profile.  This is thread safe.
489
    // 'indent' indicates whether the child will be printed w/ extra indentation
490
    // relative to the parent.
491
    // If location is non-null, child will be inserted after location.  Location must
492
    // already be added to the profile.
493
    void add_child(RuntimeProfile* child, bool indent, RuntimeProfile* location = nullptr);
494
495
    void add_child_unlock(RuntimeProfile* child, bool indent, RuntimeProfile* loc);
496
497
    /// Creates a new child profile with the given 'name'. A child profile with that name
498
    /// must not already exist. If 'prepend' is true, prepended before other child profiles,
499
    /// otherwise appended after other child profiles.
500
    RuntimeProfile* create_child(const std::string& name, bool indent = true, bool prepend = false);
501
502
    /// Returns an existing child profile with 'name', or creates it if absent. Lookup and creation
503
    /// are atomic so concurrent callers cannot race while initializing a shared profile subtree.
504
    RuntimeProfile* get_or_create_child(const std::string& name, bool indent = true,
505
                                        bool prepend = false);
506
507
    // Merges the src profile into this one, combining counters that have an identical
508
    // path. Info strings from profiles are not merged. 'src' would be a const if it
509
    // weren't for locking.
510
    // Calling this concurrently on two RuntimeProfiles in reverse order results in
511
    // undefined behavior.
512
    void merge(const RuntimeProfile* src);
513
514
    // Updates this profile w/ the thrift profile: behaves like Merge(), except
515
    // that existing counters are updated rather than added up.
516
    // Info strings matched up by key and are updated or added, depending on whether
517
    // the key has already been registered.
518
    void update(const TRuntimeProfileTree& thrift_profile);
519
520
    //Similar to `void update(const TRuntimeProfileTree& thrift_profile)`
521
    void update(const PRuntimeProfileTree& proto_profile);
522
523
    // Add a counter with 'name'/'type'.  Returns a counter object that the caller can
524
    // update.  The counter is owned by the RuntimeProfile object.
525
    // If parent_counter_name is a non-empty string, the counter is added as a child of
526
    // parent_counter_name.
527
    // If the counter already exists, the existing counter object is returned.
528
    Counter* add_counter(const std::string& name, TUnit::type type,
529
                         const std::string& parent_counter_name, int64_t level = 2);
530
531
2.81M
    Counter* add_counter(const std::string& name, TUnit::type type) {
532
2.81M
        return add_counter(name, type, RuntimeProfile::ROOT_COUNTER);
533
2.81M
    }
534
535
1.04M
    Counter* add_counter_with_level(const std::string& name, TUnit::type type, int64_t level) {
536
1.04M
        return add_counter(name, type, RuntimeProfile::ROOT_COUNTER, level);
537
1.04M
    }
538
539
    // Add a counter whose storage may outlive this profile. Repeated registration returns the same
540
    // shared counter, matching add_counter() semantics for reused scanner profiles.
541
    std::shared_ptr<Counter> add_shared_counter(
542
            const std::string& name, TUnit::type type,
543
            const std::string& parent_counter_name = RuntimeProfile::ROOT_COUNTER,
544
            int64_t level = 2);
545
546
    NonZeroCounter* add_nonzero_counter(
547
            const std::string& name, TUnit::type type,
548
            const std::string& parent_counter_name = RuntimeProfile::ROOT_COUNTER,
549
            int64_t level = 2);
550
551
    // Add a description entry under target counter.
552
    void add_description(const std::string& name, const std::string& description,
553
                         std::string parent_counter_name);
554
    // Add a derived counter with 'name'/'type'. The counter is owned by the
555
    // RuntimeProfile object.
556
    // If parent_counter_name is a non-empty string, the counter is added as a child of
557
    // parent_counter_name.
558
    // Returns nullptr if the counter already exists.
559
    DerivedCounter* add_derived_counter(const std::string& name, TUnit::type type,
560
                                        const DerivedCounterFunction& counter_fn,
561
                                        const std::string& parent_counter_name);
562
563
    ConditionCounter* add_conditition_counter(const std::string& name, TUnit::type type,
564
                                              const ConditionCounterFunction& counter_fn,
565
                                              const std::string& parent_counter_name,
566
                                              int64_t level = 2);
567
568
    // Gets the counter object with 'name'.  Returns nullptr if there is no counter with
569
    // that name.
570
    Counter* get_counter(const std::string& name);
571
572
    // Adds all counters with 'name' that are registered either in this or
573
    // in any of the child profiles to 'counters'.
574
    void get_counters(const std::string& name, std::vector<Counter*>* counters);
575
576
    // Helper to append to the "ExecOption" info string.
577
0
    void append_exec_option(const std::string& option) { add_info_string("ExecOption", option); }
578
579
    // Adds a string to the runtime profile.  If a value already exists for 'key',
580
    // the value will be updated.
581
    void add_info_string(const std::string& key, const std::string& value);
582
583
    // Returns a pointer to the info string value for 'key'.  Returns nullptr if
584
    // the key does not exist.
585
    const std::string* get_info_string(const std::string& key);
586
587
    // Returns the counter for the total elapsed time.
588
163
    Counter* total_time_counter() { return &_counter_total_time; }
589
590
    // Prints the counters in a name: value format.
591
    // Does not hold locks when it makes any function calls.
592
    void pretty_print(std::ostream* s, const std::string& prefix = "",
593
                      int64_t profile_level = 2) const;
594
26
    std::string pretty_print() const {
595
26
        std::stringstream ss;
596
26
        pretty_print(&ss);
597
26
        return ss.str();
598
26
    };
599
600
    // Serializes profile to thrift.
601
    // Does not hold locks when it makes any function calls.
602
    void to_thrift(TRuntimeProfileTree* tree, int64_t profile_level = 2);
603
    void to_thrift(std::vector<TRuntimeProfileNode>* nodes, int64_t profile_level = 2);
604
605
    // Similar to `to_thrift`.
606
    void to_proto(PRuntimeProfileTree* tree, int64_t profile_level = 2);
607
    void to_proto(google::protobuf::RepeatedPtrField<PRuntimeProfileNode>* nodes,
608
                  int64_t profile_level = 2);
609
610
    // Divides all counters by n
611
    void divide(int n);
612
613
    RuntimeProfile* get_child(std::string name);
614
615
    void get_children(std::vector<RuntimeProfile*>* children) const;
616
617
    // Gets all profiles in tree, including this one.
618
    void get_all_children(std::vector<RuntimeProfile*>* children);
619
620
    // Returns the number of counters in this profile
621
16
    int num_counters() const { return cast_set<int>(_counter_map.size()); }
622
623
    // Returns name of this profile
624
24
    const std::string& name() const { return _name; }
625
626
    // *only call this on top-level profiles*
627
    // (because it doesn't re-file child profiles)
628
0
    void set_name(const std::string& name) { _name = name; }
629
630
0
    int64_t metadata() const { return _metadata; }
631
96.6k
    void set_metadata(int64_t md) {
632
96.6k
        _is_set_metadata = true;
633
96.6k
        _metadata = md;
634
96.6k
    }
635
636
150
    bool is_set_metadata() const { return _is_set_metadata; }
637
638
0
    time_t timestamp() const { return _timestamp; }
639
0
    void set_timestamp(time_t ss) { _timestamp = ss; }
640
641
    // Derived counter function: return measured throughput as input_value/second.
642
    static int64_t units_per_second(const Counter* total_counter, const Counter* timer);
643
644
    // Derived counter function: return aggregated value
645
    static int64_t counter_sum(const std::vector<Counter*>* counters);
646
647
    /// Adds a high water mark counter to the runtime profile. Otherwise, same behavior
648
    /// as AddCounter().
649
    HighWaterMarkCounter* AddHighWaterMarkCounter(
650
            const std::string& name, TUnit::type unit,
651
            const std::string& parent_counter_name = RuntimeProfile::ROOT_COUNTER,
652
            int64_t profile_level = 2);
653
654
    // Recursively compute the fraction of the 'total_time' spent in this profile and
655
    // its children.
656
    // This function updates _local_time_percent for each profile.
657
    void compute_time_in_profile();
658
659
    void clear_children();
660
661
private:
662
    // RuntimeProfileCounterTreeNode needs to access the counter map and child counter map
663
    friend class RuntimeProfileCounterTreeNode;
664
    // Pool for allocated counters. Usually owned by the creator of this
665
    // object, but occasionally allocated in the constructor.
666
    std::unique_ptr<ObjectPool> _pool;
667
668
    // Pool for allocated counters. These counters are shared with some other objects.
669
    std::map<std::string, std::shared_ptr<Counter>> _shared_counter_pool;
670
671
    // Name for this runtime profile.
672
    std::string _name;
673
674
    // user-supplied, uninterpreted metadata.
675
    int64_t _metadata;
676
    bool _is_set_metadata = false;
677
678
    bool _is_sink = false;
679
    bool _is_set_sink = false;
680
681
    // The timestamp when the profile was modified, make sure the update is up to date.
682
    time_t _timestamp;
683
684
    /// True if this profile is an average derived from other profiles.
685
    /// All counters in this profile must be of unit AveragedCounter.
686
    bool _is_averaged_profile;
687
688
    // Map from counter names to counters.  The profile owns the memory for the
689
    // counters.
690
    using CounterMap = std::map<std::string, Counter*>;
691
    CounterMap _counter_map;
692
693
    // Map from parent counter name to a set of child counter name.
694
    // All top level counters are the child of RuntimeProfile::ROOT_COUNTER (root).
695
    using ChildCounterMap = std::map<std::string, std::set<std::string>>;
696
    ChildCounterMap _child_counter_map;
697
698
    // protects _counter_map, _counter_child_map and _bucketing_counters
699
    mutable std::mutex _counter_map_lock;
700
701
    // Child profiles.  Does not own memory.
702
    // We record children in both a map (to facilitate updates) and a vector
703
    // (to print things in the order they were registered)
704
    using ChildMap = std::map<std::string, RuntimeProfile*>;
705
    ChildMap _child_map;
706
    // vector of (profile, indentation flag)
707
    using ChildVector = std::vector<std::pair<RuntimeProfile*, bool>>;
708
    ChildVector _children;
709
    mutable std::mutex _children_lock; // protects _child_map and _children
710
711
    using InfoStrings = std::map<std::string, std::string>;
712
    InfoStrings _info_strings;
713
714
    // Keeps track of the order in which InfoStrings are displayed when printed
715
    using InfoStringsDisplayOrder = std::vector<std::string>;
716
    InfoStringsDisplayOrder _info_strings_display_order;
717
718
    // Protects _info_strings and _info_strings_display_order
719
    mutable std::mutex _info_strings_lock;
720
721
    Counter _counter_total_time;
722
    // Time spent in just in this profile (i.e. not the children) as a fraction
723
    // of the total time in the entire profile tree.
724
    double _local_time_percent;
725
726
    // update a subtree of profiles from nodes, rooted at *idx.
727
    // On return, *idx points to the node immediately following this subtree.
728
    void update(const std::vector<TRuntimeProfileNode>& nodes, int* idx);
729
730
    // Similar to `void update(const std::vector<TRuntimeProfileNode>& nodes, int* idx)`
731
    void update(const google::protobuf::RepeatedPtrField<PRuntimeProfileNode>& nodes, int* idx);
732
733
    // Helper function to compute compute the fraction of the total time spent in
734
    // this profile and its children.
735
    // Called recursively.
736
    void compute_time_in_profile(int64_t total_time);
737
738
    // Print the child counters of the given counter name
739
    static void print_child_counters(const std::string& prefix, const std::string& counter_name,
740
                                     const CounterMap& counter_map,
741
                                     const ChildCounterMap& child_counter_map, std::ostream* s);
742
};
743
744
// Utility class to update the counter at object construction and destruction.
745
// When the object is constructed, decrement the counter by val.
746
// When the object goes out of scope, increment the counter by val.
747
class ScopedCounter {
748
public:
749
0
    ScopedCounter(RuntimeProfile::Counter* counter, int64_t val) : _val(val), _counter(counter) {
750
0
        if (counter == nullptr) {
751
0
            return;
752
0
        }
753
0
754
0
        _counter->update(-1L * _val);
755
0
    }
756
757
    // Increment the counter when object is destroyed
758
0
    ~ScopedCounter() {
759
0
        if (_counter != nullptr) {
760
0
            _counter->update(_val);
761
0
        }
762
0
    }
763
764
    // Disable copy constructor and assignment
765
    ScopedCounter(const ScopedCounter& counter) = delete;
766
    ScopedCounter& operator=(const ScopedCounter& counter) = delete;
767
768
private:
769
    int64_t _val;
770
    RuntimeProfile::Counter* _counter = nullptr;
771
};
772
773
// Utility class to update time elapsed when the object goes out of scope.
774
// 'T' must implement the stopWatch "interface" (start,stop,elapsed_time) but
775
// we use templates not to pay for virtual function overhead.
776
template <class T, typename Bool = bool>
777
class ScopedTimer {
778
public:
779
    ScopedTimer(RuntimeProfile::Counter* counter, const Bool* is_cancelled = nullptr)
780
2.03M
            : _counter(counter), _is_cancelled(is_cancelled) {
781
2.03M
        if (counter == nullptr) {
782
4.72k
            return;
783
4.72k
        }
784
2.03M
        DCHECK_EQ(counter->type(), TUnit::TIME_NS);
785
2.03M
        _sw.start();
786
2.03M
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbEC2EPNS_14RuntimeProfile7CounterEPKb
Line
Count
Source
780
2.03M
            : _counter(counter), _is_cancelled(is_cancelled) {
781
2.03M
        if (counter == nullptr) {
782
4.72k
            return;
783
4.72k
        }
784
2.03M
        DCHECK_EQ(counter->type(), TUnit::TIME_NS);
785
2.03M
        _sw.start();
786
2.03M
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbEC2EPNS_14RuntimeProfile7CounterEPKb
Line
Count
Source
780
106
            : _counter(counter), _is_cancelled(is_cancelled) {
781
106
        if (counter == nullptr) {
782
0
            return;
783
0
        }
784
106
        DCHECK_EQ(counter->type(), TUnit::TIME_NS);
785
106
        _sw.start();
786
106
    }
787
788
    void stop() { _sw.stop(); }
789
790
    void start() { _sw.start(); }
791
792
2.03M
    bool is_cancelled() { return _is_cancelled != nullptr && *_is_cancelled; }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbE12is_cancelledEv
Line
Count
Source
792
2.03M
    bool is_cancelled() { return _is_cancelled != nullptr && *_is_cancelled; }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbE12is_cancelledEv
Line
Count
Source
792
106
    bool is_cancelled() { return _is_cancelled != nullptr && *_is_cancelled; }
793
794
2.03M
    void UpdateCounter() {
795
2.03M
        if (_counter != nullptr && !is_cancelled()) {
796
2.03M
            _counter->update(_sw.elapsed_time());
797
2.03M
        }
798
2.03M
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbE13UpdateCounterEv
Line
Count
Source
794
2.03M
    void UpdateCounter() {
795
2.03M
        if (_counter != nullptr && !is_cancelled()) {
796
2.03M
            _counter->update(_sw.elapsed_time());
797
2.03M
        }
798
2.03M
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbE13UpdateCounterEv
Line
Count
Source
794
106
    void UpdateCounter() {
795
106
        if (_counter != nullptr && !is_cancelled()) {
796
106
            _counter->update(_sw.elapsed_time());
797
106
        }
798
106
    }
799
800
    // Update counter when object is destroyed
801
2.03M
    ~ScopedTimer() {
802
2.03M
        if (_counter == nullptr) {
803
4.72k
            return;
804
4.72k
        }
805
2.03M
        _sw.stop();
806
2.03M
        UpdateCounter();
807
2.03M
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbED2Ev
Line
Count
Source
801
2.03M
    ~ScopedTimer() {
802
2.03M
        if (_counter == nullptr) {
803
4.72k
            return;
804
4.72k
        }
805
2.03M
        _sw.stop();
806
2.03M
        UpdateCounter();
807
2.03M
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbED2Ev
Line
Count
Source
801
106
    ~ScopedTimer() {
802
106
        if (_counter == nullptr) {
803
0
            return;
804
0
        }
805
106
        _sw.stop();
806
106
        UpdateCounter();
807
106
    }
808
809
    // Disable copy constructor and assignment
810
    ScopedTimer(const ScopedTimer& timer) = delete;
811
    ScopedTimer& operator=(const ScopedTimer& timer) = delete;
812
813
private:
814
    T _sw;
815
    RuntimeProfile::Counter* _counter = nullptr;
816
    const Bool* _is_cancelled = nullptr;
817
};
818
819
// Utility class to update time elapsed when the object goes out of scope.
820
// 'T' must implement the stopWatch "interface" (start,stop,elapsed_time) but
821
// we use templates not to pay for virtual function overhead.
822
template <class T, class C>
823
class ScopedRawTimer {
824
public:
825
4.45M
    ScopedRawTimer(C* counter) : _counter(counter) { _sw.start(); }
_ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEElEC2EPl
Line
Count
Source
825
4.45M
    ScopedRawTimer(C* counter) : _counter(counter) { _sw.start(); }
Unexecuted instantiation: _ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEESt6atomicIlEEC2EPS4_
826
    // Update counter when object is destroyed
827
4.44M
    ~ScopedRawTimer() { *_counter += _sw.elapsed_time(); }
_ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEElED2Ev
Line
Count
Source
827
4.44M
    ~ScopedRawTimer() { *_counter += _sw.elapsed_time(); }
Unexecuted instantiation: _ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEESt6atomicIlEED2Ev
828
829
    // Disable copy constructor and assignment
830
    ScopedRawTimer(const ScopedRawTimer& timer) = delete;
831
    ScopedRawTimer& operator=(const ScopedRawTimer& timer) = delete;
832
833
private:
834
    T _sw;
835
    C* _counter = nullptr;
836
};
837
#include "common/compile_check_end.h"
838
} // namespace doris