Coverage Report

Created: 2025-04-11 12:31

/root/doris/be/src/util/runtime_profile.h
Line
Count
Source (jump to first uncovered line)
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 <glog/logging.h>
26
#include <stdint.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <cstdint>
31
#include <functional>
32
#include <iostream>
33
#include <map>
34
#include <memory>
35
#include <mutex>
36
#include <set>
37
#include <string>
38
#include <utility>
39
#include <vector>
40
41
#include "common/compiler_util.h" // IWYU pragma: keep
42
#include "common/logging.h"
43
#include "util/binary_cast.hpp"
44
#include "util/container_util.hpp"
45
#include "util/pretty_printer.h"
46
#include "util/stopwatch.hpp"
47
48
namespace doris {
49
class TRuntimeProfileNode;
50
class TRuntimeProfileTree;
51
class RuntimeProfileCounterTreeNode;
52
53
// Some macro magic to generate unique ids using __COUNTER__
54
1.83M
#define CONCAT_IMPL(x, y) x##y
55
1.83M
#define MACRO_CONCAT(x, y) CONCAT_IMPL(x, y)
56
57
#define ADD_LABEL_COUNTER(profile, name) (profile)->add_counter(name, TUnit::NONE)
58
#define ADD_LABEL_COUNTER_WITH_LEVEL(profile, name, level) \
59
    (profile)->add_counter_with_level(name, TUnit::NONE, level)
60
15.8k
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
61
#define ADD_COUNTER_WITH_LEVEL(profile, name, type, level) \
62
1.78k
    (profile)->add_counter_with_level(name, type, level)
63
3.56k
#define ADD_TIMER(profile, name) (profile)->add_counter(name, TUnit::TIME_NS)
64
#define ADD_TIMER_WITH_LEVEL(profile, name, level) \
65
3.18k
    (profile)->add_counter_with_level(name, TUnit::TIME_NS, level)
66
1
#define ADD_CHILD_COUNTER(profile, name, type, parent) (profile)->add_counter(name, type, parent)
67
#define ADD_CHILD_COUNTER_WITH_LEVEL(profile, name, type, parent, level) \
68
18
    (profile)->add_counter(name, type, parent, level)
69
673
#define ADD_CHILD_TIMER(profile, name, parent) (profile)->add_counter(name, TUnit::TIME_NS, parent)
70
#define ADD_CHILD_TIMER_WITH_LEVEL(profile, name, parent, level) \
71
23
    (profile)->add_counter(name, TUnit::TIME_NS, parent, level)
72
797k
#define SCOPED_TIMER(c) ScopedTimer<MonotonicStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
73
#define SCOPED_TIMER_ATOMIC(c) \
74
    ScopedTimer<MonotonicStopWatch, std::atomic_bool> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
75
#define SCOPED_CPU_TIMER(c) \
76
23
    ScopedTimer<ThreadCpuStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
77
#define CANCEL_SAFE_SCOPED_TIMER(c, is_cancelled) \
78
    ScopedTimer<MonotonicStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c, is_cancelled)
79
#define SCOPED_RAW_TIMER(c)                                                                  \
80
1.03M
    doris::ScopedRawTimer<doris::MonotonicStopWatch, int64_t> MACRO_CONCAT(SCOPED_RAW_TIMER, \
81
1.03M
                                                                           __COUNTER__)(c)
82
#define SCOPED_ATOMIC_TIMER(c)                                                                 \
83
0
    ScopedRawTimer<MonotonicStopWatch, std::atomic<int64_t>> MACRO_CONCAT(SCOPED_ATOMIC_TIMER, \
84
0
                                                                          __COUNTER__)(c)
85
18.5k
#define COUNTER_UPDATE(c, v) (c)->update(v)
86
1.04k
#define COUNTER_SET(c, v) (c)->set(v)
87
88
class ObjectPool;
89
90
// Runtime profile is a group of profiling counters.  It supports adding named counters
91
// and being able to serialize and deserialize them.
92
// The profiles support a tree structure to form a hierarchy of counters.
93
// Runtime profiles supports measuring wall clock rate based counters.  There is a
94
// single thread per process that will convert an amount (i.e. bytes) counter to a
95
// corresponding rate based counter.  This thread wakes up at fixed intervals and updates
96
// all of the rate counters.
97
// Thread-safe.
98
class RuntimeProfile {
99
public:
100
    static std::unique_ptr<RuntimeProfile> from_thrift(const TRuntimeProfileTree& node);
101
102
    // The root counter name for all top level counters.
103
    static const std::string ROOT_COUNTER;
104
    class Counter {
105
    public:
106
        Counter(TUnit::type type, int64_t value = 0, int64_t level = 3)
107
57.6k
                : _value(value), _type(type), _level(level) {}
108
57.5k
        virtual ~Counter() = default;
109
110
4
        virtual Counter* clone() const { return new Counter(type(), value(), _level); }
111
112
1.60M
        virtual void update(int64_t delta) { _value.fetch_add(delta, std::memory_order_relaxed); }
113
114
0
        void bit_or(int64_t delta) { _value.fetch_or(delta, std::memory_order_relaxed); }
115
116
1.27k
        virtual void set(int64_t value) { _value.store(value, std::memory_order_relaxed); }
117
118
0
        virtual void set(double value) {
119
0
            DCHECK_EQ(sizeof(value), sizeof(int64_t));
120
0
            _value.store(binary_cast<double, int64_t>(value), std::memory_order_relaxed);
121
0
        }
122
123
38.4k
        virtual int64_t value() const { return _value.load(std::memory_order_relaxed); }
124
125
0
        virtual double double_value() const {
126
0
            return binary_cast<int64_t, double>(_value.load(std::memory_order_relaxed));
127
0
        }
128
129
36.7k
        virtual TCounter to_thrift(const std::string& name) const {
130
36.7k
            TCounter counter;
131
36.7k
            counter.name = name;
132
36.7k
            counter.value = this->value();
133
36.7k
            counter.type = this->type();
134
36.7k
            counter.__set_level(this->_level);
135
36.7k
            return counter;
136
36.7k
        }
137
138
        virtual void pretty_print(std::ostream* s, const std::string& prefix,
139
275
                                  const std::string& name) const {
140
275
            std::ostream& stream = *s;
141
275
            stream << prefix << "   - " << name << ": "
142
275
                   << PrettyPrinter::print(_value.load(std::memory_order_relaxed), type())
143
275
                   << std::endl;
144
275
        }
145
146
834k
        TUnit::type type() const { return _type; }
147
148
36.9k
        virtual int64_t level() const { return _level; }
149
150
3
        void set_level(int64_t level) { _level = level; }
151
152
        bool operator==(const Counter& other) const;
153
154
    private:
155
        friend class RuntimeProfile;
156
        friend class RuntimeProfileCounterTreeNode;
157
158
        std::atomic<int64_t> _value;
159
        TUnit::type _type;
160
        int64_t _level;
161
    };
162
163
    /// A counter that keeps track of the highest value seen (reporting that
164
    /// as value()) and the current value.
165
    class HighWaterMarkCounter : public Counter {
166
    public:
167
        HighWaterMarkCounter(TUnit::type unit, int64_t level, const std::string& parent_name,
168
                             int64_t value = 0, int64_t current_value = 0)
169
                : Counter(unit, value, level),
170
                  current_value_(current_value),
171
693
                  _parent_name(parent_name) {}
172
173
0
        virtual Counter* clone() const override {
174
0
            return new HighWaterMarkCounter(type(), level(), parent_name(), value(),
175
0
                                            current_value());
176
0
        }
177
178
2.62k
        void add(int64_t delta) {
179
2.62k
            current_value_.fetch_add(delta, std::memory_order_relaxed);
180
2.62k
            if (delta > 0) {
181
1.28k
                UpdateMax(current_value_);
182
1.28k
            }
183
2.62k
        }
184
2.62k
        virtual void update(int64_t delta) override { add(delta); }
185
186
2
        TCounter to_thrift(const std::string& name) const override {
187
2
            TCounter counter;
188
2
            counter.name = std::move(name);
189
2
            counter.value = current_value();
190
2
            counter.type = type();
191
2
            counter.__set_level(level());
192
2
            return counter;
193
2
        }
194
195
2
        TCounter to_thrift_peak(std::string name) {
196
2
            TCounter counter;
197
2
            counter.name = std::move(name);
198
2
            counter.value = value();
199
2
            counter.type = type();
200
2
            counter.__set_level(level());
201
2
            return counter;
202
2
        }
203
204
        virtual void pretty_print(std::ostream* s, const std::string& prefix,
205
43
                                  const std::string& name) const override {
206
43
            std::ostream& stream = *s;
207
43
            stream << prefix << "   - " << name
208
43
                   << " Current: " << PrettyPrinter::print(current_value(), type()) << " (Peak: "
209
43
                   << PrettyPrinter::print(_value.load(std::memory_order_relaxed), type()) << ")"
210
43
                   << std::endl;
211
43
        }
212
213
        /// Tries to increase the current value by delta. If current_value() + delta
214
        /// exceeds max, return false and current_value is not changed.
215
0
        bool try_add(int64_t delta, int64_t max) {
216
0
            while (true) {
217
0
                int64_t old_val = current_value_.load(std::memory_order_relaxed);
218
0
                int64_t new_val = old_val + delta;
219
0
                if (UNLIKELY(new_val > max)) return false;
220
0
                if (LIKELY(current_value_.compare_exchange_weak(old_val, new_val,
221
0
                                                                std::memory_order_relaxed))) {
222
0
                    UpdateMax(new_val);
223
0
                    return true;
224
0
                }
225
0
            }
226
0
        }
227
228
248
        void set(int64_t v) override {
229
248
            current_value_.store(v, std::memory_order_relaxed);
230
248
            UpdateMax(v);
231
248
        }
232
233
45
        int64_t current_value() const { return current_value_.load(std::memory_order_relaxed); }
234
235
2
        std::string parent_name() const { return _parent_name; }
236
237
    private:
238
        /// Set '_value' to 'v' if 'v' is larger than '_value'. The entire operation is
239
        /// atomic.
240
1.53k
        void UpdateMax(int64_t v) {
241
1.53k
            while (true) {
242
1.53k
                int64_t old_max = _value.load(std::memory_order_relaxed);
243
1.53k
                int64_t new_max = std::max(old_max, v);
244
1.53k
                if (new_max == old_max) {
245
1.25k
                    break; // Avoid atomic update.
246
1.25k
                }
247
278
                if (LIKELY(_value.compare_exchange_weak(old_max, new_max,
248
278
                                                        std::memory_order_relaxed))) {
249
278
                    break;
250
278
                }
251
278
            }
252
1.53k
        }
253
254
        /// The current value of the counter. _value in the super class represents
255
        /// the high water mark.
256
        std::atomic<int64_t> current_value_;
257
258
        const std::string _parent_name;
259
    };
260
261
    using DerivedCounterFunction = std::function<int64_t()>;
262
263
    // A DerivedCounter also has a name and type, but the value is computed.
264
    // Do not call Set() and Update().
265
    class DerivedCounter : public Counter {
266
    public:
267
        DerivedCounter(TUnit::type type, const DerivedCounterFunction& counter_fn,
268
                       int64_t value = 0, int64_t level = 1)
269
8
                : Counter(type, value, level), _counter_fn(counter_fn) {}
270
271
0
        virtual Counter* clone() const override {
272
0
            return new DerivedCounter(type(), _counter_fn, value(), level());
273
0
        }
274
275
3
        int64_t value() const override { return _counter_fn(); }
276
277
    private:
278
        DerivedCounterFunction _counter_fn;
279
    };
280
281
    // NonZeroCounter will not be converted to Thrift if the value is 0.
282
    class NonZeroCounter : public Counter {
283
    public:
284
        NonZeroCounter(TUnit::type type, int64_t level, const std::string& parent_name,
285
                       int64_t value = 0)
286
34
                : Counter(type, value, level), _parent_name(parent_name) {}
287
288
0
        virtual Counter* clone() const override {
289
0
            return new NonZeroCounter(type(), level(), parent_name(), value());
290
0
        }
291
292
1
        std::string parent_name() const { return _parent_name; }
293
294
    private:
295
        const std::string _parent_name;
296
    };
297
298
    class DescriptionEntry : public Counter {
299
    public:
300
        DescriptionEntry(const std::string& name, const std::string& description)
301
1
                : Counter(TUnit::NONE, 0, 2), _description(description), _name(name) {}
302
303
0
        virtual Counter* clone() const override {
304
0
            return new DescriptionEntry(_name, _description);
305
0
        }
306
307
0
        void set(int64_t value) override {
308
            // Do nothing
309
0
        }
310
0
        void set(double value) override {
311
            // Do nothing
312
0
        }
313
0
        void update(int64_t delta) override {
314
            // Do nothing
315
0
        }
316
317
1
        TCounter to_thrift(const std::string& name) const override {
318
1
            TCounter counter;
319
1
            counter.name = name;
320
1
            counter.__set_level(2);
321
1
            counter.__set_description(_description);
322
1
            return counter;
323
1
        }
324
325
    private:
326
        const std::string _description;
327
        const std::string _name;
328
    };
329
330
    // Create a runtime profile object with 'name'.
331
    RuntimeProfile(const std::string& name, bool is_averaged_profile = false);
332
333
    ~RuntimeProfile();
334
335
    // Adds a child profile.  This is thread safe.
336
    // 'indent' indicates whether the child will be printed w/ extra indentation
337
    // relative to the parent.
338
    // If location is non-null, child will be inserted after location.  Location must
339
    // already be added to the profile.
340
    void add_child(RuntimeProfile* child, bool indent, RuntimeProfile* location = nullptr);
341
342
    void add_child_unlock(RuntimeProfile* child, bool indent, RuntimeProfile* loc);
343
344
    /// Creates a new child profile with the given 'name'. A child profile with that name
345
    /// must not already exist. If 'prepend' is true, prepended before other child profiles,
346
    /// otherwise appended after other child profiles.
347
    RuntimeProfile* create_child(const std::string& name, bool indent = true, bool prepend = false);
348
349
    // Merges the src profile into this one, combining counters that have an identical
350
    // path. Info strings from profiles are not merged. 'src' would be a const if it
351
    // weren't for locking.
352
    // Calling this concurrently on two RuntimeProfiles in reverse order results in
353
    // undefined behavior.
354
    void merge(RuntimeProfile* src);
355
356
    // Updates this profile w/ the thrift profile: behaves like Merge(), except
357
    // that existing counters are updated rather than added up.
358
    // Info strings matched up by key and are updated or added, depending on whether
359
    // the key has already been registered.
360
    void update(const TRuntimeProfileTree& thrift_profile);
361
362
    // Add a counter with 'name'/'type'.  Returns a counter object that the caller can
363
    // update.  The counter is owned by the RuntimeProfile object.
364
    // If parent_counter_name is a non-empty string, the counter is added as a child of
365
    // parent_counter_name.
366
    // If the counter already exists, the existing counter object is returned.
367
    Counter* add_counter(const std::string& name, TUnit::type type,
368
                         const std::string& parent_counter_name, int64_t level = 2);
369
370
20.4k
    Counter* add_counter(const std::string& name, TUnit::type type) {
371
20.4k
        return add_counter(name, type, RuntimeProfile::ROOT_COUNTER);
372
20.4k
    }
373
374
4.96k
    Counter* add_counter_with_level(const std::string& name, TUnit::type type, int64_t level) {
375
4.96k
        return add_counter(name, type, RuntimeProfile::ROOT_COUNTER, level);
376
4.96k
    }
377
378
    NonZeroCounter* add_nonzero_counter(
379
            const std::string& name, TUnit::type type,
380
            const std::string& parent_counter_name = RuntimeProfile::ROOT_COUNTER,
381
            int64_t level = 2);
382
383
    // Add a description entry under target counter.
384
    void add_description(const std::string& name, const std::string& description,
385
                         std::string parent_counter_name);
386
    // Add a derived counter with 'name'/'type'. The counter is owned by the
387
    // RuntimeProfile object.
388
    // If parent_counter_name is a non-empty string, the counter is added as a child of
389
    // parent_counter_name.
390
    // Returns nullptr if the counter already exists.
391
    DerivedCounter* add_derived_counter(const std::string& name, TUnit::type type,
392
                                        const DerivedCounterFunction& counter_fn,
393
                                        const std::string& parent_counter_name);
394
395
    // Gets the counter object with 'name'.  Returns nullptr if there is no counter with
396
    // that name.
397
    Counter* get_counter(const std::string& name);
398
399
    // Adds all counters with 'name' that are registered either in this or
400
    // in any of the child profiles to 'counters'.
401
    void get_counters(const std::string& name, std::vector<Counter*>* counters);
402
403
    // Helper to append to the "ExecOption" info string.
404
0
    void append_exec_option(const std::string& option) { add_info_string("ExecOption", option); }
405
406
    // Adds a string to the runtime profile.  If a value already exists for 'key',
407
    // the value will be updated.
408
    void add_info_string(const std::string& key, const std::string& value);
409
410
    // Returns a pointer to the info string value for 'key'.  Returns nullptr if
411
    // the key does not exist.
412
    const std::string* get_info_string(const std::string& key);
413
414
    // Returns the counter for the total elapsed time.
415
60
    Counter* total_time_counter() { return &_counter_total_time; }
416
417
    // Prints the counters in a name: value format.
418
    // Does not hold locks when it makes any function calls.
419
    void pretty_print(std::ostream* s, const std::string& prefix = "",
420
                      int64_t profile_level = 2) const;
421
16
    std::string pretty_print() const {
422
16
        std::stringstream ss;
423
16
        pretty_print(&ss);
424
16
        return ss.str();
425
16
    };
426
427
    // Serializes profile to thrift.
428
    // Does not hold locks when it makes any function calls.
429
    void to_thrift(TRuntimeProfileTree* tree, int64_t profile_level = 2);
430
    void to_thrift(std::vector<TRuntimeProfileNode>* nodes, int64_t profile_level = 2);
431
432
    // Divides all counters by n
433
    void divide(int n);
434
435
    void get_children(std::vector<RuntimeProfile*>* children);
436
437
    // Gets all profiles in tree, including this one.
438
    void get_all_children(std::vector<RuntimeProfile*>* children);
439
440
    // Returns the number of counters in this profile
441
8
    int num_counters() const { return _counter_map.size(); }
442
443
    // Returns name of this profile
444
12
    const std::string& name() const { return _name; }
445
446
    // *only call this on top-level profiles*
447
    // (because it doesn't re-file child profiles)
448
0
    void set_name(const std::string& name) { _name = name; }
449
450
0
    int64_t metadata() const { return _metadata; }
451
399
    void set_metadata(int64_t md) {
452
399
        _is_set_metadata = true;
453
399
        _metadata = md;
454
399
    }
455
456
110
    bool is_set_metadata() const { return _is_set_metadata; }
457
458
0
    time_t timestamp() const { return _timestamp; }
459
0
    void set_timestamp(time_t ss) { _timestamp = ss; }
460
461
    // Derived counter function: return measured throughput as input_value/second.
462
    static int64_t units_per_second(const Counter* total_counter, const Counter* timer);
463
464
    // Derived counter function: return aggregated value
465
    static int64_t counter_sum(const std::vector<Counter*>* counters);
466
467
    /// Adds a high water mark counter to the runtime profile. Otherwise, same behavior
468
    /// as AddCounter().
469
    HighWaterMarkCounter* AddHighWaterMarkCounter(
470
            const std::string& name, TUnit::type unit,
471
            const std::string& parent_counter_name = RuntimeProfile::ROOT_COUNTER,
472
            int64_t profile_level = 2);
473
474
    // Recursively compute the fraction of the 'total_time' spent in this profile and
475
    // its children.
476
    // This function updates _local_time_percent for each profile.
477
    void compute_time_in_profile();
478
479
    void clear_children();
480
481
private:
482
    // RuntimeProfileCounterTreeNode needs to access the counter map and child counter map
483
    friend class RuntimeProfileCounterTreeNode;
484
    // Pool for allocated counters. Usually owned by the creator of this
485
    // object, but occasionally allocated in the constructor.
486
    std::unique_ptr<ObjectPool> _pool;
487
488
    // Pool for allocated counters. These counters are shared with some other objects.
489
    std::map<std::string, std::shared_ptr<HighWaterMarkCounter>> _shared_counter_pool;
490
491
    // Name for this runtime profile.
492
    std::string _name;
493
494
    // user-supplied, uninterpreted metadata.
495
    int64_t _metadata;
496
    bool _is_set_metadata = false;
497
498
    bool _is_sink = false;
499
    bool _is_set_sink = false;
500
501
    // The timestamp when the profile was modified, make sure the update is up to date.
502
    time_t _timestamp;
503
504
    /// True if this profile is an average derived from other profiles.
505
    /// All counters in this profile must be of unit AveragedCounter.
506
    bool _is_averaged_profile;
507
508
    // Map from counter names to counters.  The profile owns the memory for the
509
    // counters.
510
    using CounterMap = std::map<std::string, Counter*>;
511
    CounterMap _counter_map;
512
513
    // Map from parent counter name to a set of child counter name.
514
    // All top level counters are the child of RuntimeProfile::ROOT_COUNTER (root).
515
    using ChildCounterMap = std::map<std::string, std::set<std::string>>;
516
    ChildCounterMap _child_counter_map;
517
518
    // protects _counter_map, _counter_child_map and _bucketing_counters
519
    mutable std::mutex _counter_map_lock;
520
521
    // Child profiles.  Does not own memory.
522
    // We record children in both a map (to facilitate updates) and a vector
523
    // (to print things in the order they were registered)
524
    using ChildMap = std::map<std::string, RuntimeProfile*>;
525
    ChildMap _child_map;
526
    // vector of (profile, indentation flag)
527
    using ChildVector = std::vector<std::pair<RuntimeProfile*, bool>>;
528
    ChildVector _children;
529
    mutable std::mutex _children_lock; // protects _child_map and _children
530
531
    using InfoStrings = std::map<std::string, std::string>;
532
    InfoStrings _info_strings;
533
534
    // Keeps track of the order in which InfoStrings are displayed when printed
535
    using InfoStringsDisplayOrder = std::vector<std::string>;
536
    InfoStringsDisplayOrder _info_strings_display_order;
537
538
    // Protects _info_strings and _info_strings_display_order
539
    mutable std::mutex _info_strings_lock;
540
541
    Counter _counter_total_time;
542
    // Time spent in just in this profile (i.e. not the children) as a fraction
543
    // of the total time in the entire profile tree.
544
    double _local_time_percent;
545
546
    // update a subtree of profiles from nodes, rooted at *idx.
547
    // On return, *idx points to the node immediately following this subtree.
548
    void update(const std::vector<TRuntimeProfileNode>& nodes, int* idx);
549
550
    // Helper function to compute compute the fraction of the total time spent in
551
    // this profile and its children.
552
    // Called recursively.
553
    void compute_time_in_profile(int64_t total_time);
554
555
    // Print the child counters of the given counter name
556
    static void print_child_counters(const std::string& prefix, const std::string& counter_name,
557
                                     const CounterMap& counter_map,
558
                                     const ChildCounterMap& child_counter_map, std::ostream* s);
559
};
560
561
// Utility class to update the counter at object construction and destruction.
562
// When the object is constructed, decrement the counter by val.
563
// When the object goes out of scope, increment the counter by val.
564
class ScopedCounter {
565
public:
566
0
    ScopedCounter(RuntimeProfile::Counter* counter, int64_t val) : _val(val), _counter(counter) {
567
0
        if (counter == nullptr) {
568
0
            return;
569
0
        }
570
0
571
0
        _counter->update(-1L * _val);
572
0
    }
573
574
    // Increment the counter when object is destroyed
575
0
    ~ScopedCounter() {
576
0
        if (_counter != nullptr) {
577
0
            _counter->update(_val);
578
0
        }
579
0
    }
580
581
    // Disable copy constructor and assignment
582
    ScopedCounter(const ScopedCounter& counter) = delete;
583
    ScopedCounter& operator=(const ScopedCounter& counter) = delete;
584
585
private:
586
    int64_t _val;
587
    RuntimeProfile::Counter* _counter = nullptr;
588
};
589
590
// Utility class to update time elapsed when the object goes out of scope.
591
// 'T' must implement the stopWatch "interface" (start,stop,elapsed_time) but
592
// we use templates not to pay for virtual function overhead.
593
template <class T, typename Bool = bool>
594
class ScopedTimer {
595
public:
596
    ScopedTimer(RuntimeProfile::Counter* counter, const Bool* is_cancelled = nullptr)
597
797k
            : _counter(counter), _is_cancelled(is_cancelled) {
598
797k
        if (counter == nullptr) {
599
97
            return;
600
97
        }
601
797k
        DCHECK_EQ(counter->type(), TUnit::TIME_NS);
602
797k
        _sw.start();
603
797k
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbEC2EPNS_14RuntimeProfile7CounterEPKb
Line
Count
Source
597
797k
            : _counter(counter), _is_cancelled(is_cancelled) {
598
797k
        if (counter == nullptr) {
599
97
            return;
600
97
        }
601
797k
        DCHECK_EQ(counter->type(), TUnit::TIME_NS);
602
797k
        _sw.start();
603
797k
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbEC2EPNS_14RuntimeProfile7CounterEPKb
Line
Count
Source
597
23
            : _counter(counter), _is_cancelled(is_cancelled) {
598
23
        if (counter == nullptr) {
599
0
            return;
600
0
        }
601
23
        DCHECK_EQ(counter->type(), TUnit::TIME_NS);
602
23
        _sw.start();
603
23
    }
604
605
    void stop() { _sw.stop(); }
606
607
    void start() { _sw.start(); }
608
609
797k
    bool is_cancelled() { return _is_cancelled != nullptr && *_is_cancelled; }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbE12is_cancelledEv
Line
Count
Source
609
797k
    bool is_cancelled() { return _is_cancelled != nullptr && *_is_cancelled; }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbE12is_cancelledEv
Line
Count
Source
609
23
    bool is_cancelled() { return _is_cancelled != nullptr && *_is_cancelled; }
610
611
797k
    void UpdateCounter() {
612
797k
        if (_counter != nullptr && !is_cancelled()) {
613
797k
            _counter->update(_sw.elapsed_time());
614
797k
        }
615
797k
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbE13UpdateCounterEv
Line
Count
Source
611
797k
    void UpdateCounter() {
612
797k
        if (_counter != nullptr && !is_cancelled()) {
613
797k
            _counter->update(_sw.elapsed_time());
614
797k
        }
615
797k
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbE13UpdateCounterEv
Line
Count
Source
611
23
    void UpdateCounter() {
612
23
        if (_counter != nullptr && !is_cancelled()) {
613
23
            _counter->update(_sw.elapsed_time());
614
23
        }
615
23
    }
616
617
    // Update counter when object is destroyed
618
797k
    ~ScopedTimer() {
619
797k
        if (_counter == nullptr) {
620
97
            return;
621
97
        }
622
797k
        _sw.stop();
623
797k
        UpdateCounter();
624
797k
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi1EEEbED2Ev
Line
Count
Source
618
797k
    ~ScopedTimer() {
619
797k
        if (_counter == nullptr) {
620
97
            return;
621
97
        }
622
797k
        _sw.stop();
623
797k
        UpdateCounter();
624
797k
    }
_ZN5doris11ScopedTimerINS_15CustomStopWatchILi3EEEbED2Ev
Line
Count
Source
618
23
    ~ScopedTimer() {
619
23
        if (_counter == nullptr) {
620
0
            return;
621
0
        }
622
23
        _sw.stop();
623
23
        UpdateCounter();
624
23
    }
625
626
    // Disable copy constructor and assignment
627
    ScopedTimer(const ScopedTimer& timer) = delete;
628
    ScopedTimer& operator=(const ScopedTimer& timer) = delete;
629
630
private:
631
    T _sw;
632
    RuntimeProfile::Counter* _counter = nullptr;
633
    const Bool* _is_cancelled = nullptr;
634
};
635
636
// Utility class to update time elapsed when the object goes out of scope.
637
// 'T' must implement the stopWatch "interface" (start,stop,elapsed_time) but
638
// we use templates not to pay for virtual function overhead.
639
template <class T, class C>
640
class ScopedRawTimer {
641
public:
642
1.03M
    ScopedRawTimer(C* counter) : _counter(counter) { _sw.start(); }
_ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEElEC2EPl
Line
Count
Source
642
1.03M
    ScopedRawTimer(C* counter) : _counter(counter) { _sw.start(); }
Unexecuted instantiation: _ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEESt6atomicIlEEC2EPS4_
643
    // Update counter when object is destroyed
644
1.03M
    ~ScopedRawTimer() { *_counter += _sw.elapsed_time(); }
_ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEElED2Ev
Line
Count
Source
644
1.03M
    ~ScopedRawTimer() { *_counter += _sw.elapsed_time(); }
Unexecuted instantiation: _ZN5doris14ScopedRawTimerINS_15CustomStopWatchILi1EEESt6atomicIlEED2Ev
645
646
    // Disable copy constructor and assignment
647
    ScopedRawTimer(const ScopedRawTimer& timer) = delete;
648
    ScopedRawTimer& operator=(const ScopedRawTimer& timer) = delete;
649
650
private:
651
    T _sw;
652
    C* _counter = nullptr;
653
};
654
655
} // namespace doris