1 //===-- Timer.h -------------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_UTILITY_TIMER_H
10 #define LLDB_UTILITY_TIMER_H
11 
12 #include "lldb/lldb-defines.h"
13 #include "llvm/Support/Chrono.h"
14 #include <atomic>
15 #include <stdint.h>
16 
17 namespace lldb_private {
18 class Stream;
19 
20 /// \class Timer Timer.h "lldb/Utility/Timer.h"
21 /// A timer class that simplifies common timing metrics.
22 
23 class Timer {
24 public:
25   class Category {
26   public:
27     explicit Category(const char *category_name);
28 
29   private:
30     friend class Timer;
31     const char *m_name;
32     std::atomic<uint64_t> m_nanos;
33     std::atomic<uint64_t> m_nanos_total;
34     std::atomic<uint64_t> m_count;
35     std::atomic<Category *> m_next;
36 
37     Category(const Category &) = delete;
38     const Category &operator=(const Category &) = delete;
39   };
40 
41   /// Default constructor.
42   Timer(Category &category, const char *format, ...)
43       __attribute__((format(printf, 3, 4)));
44 
45   /// Destructor
46   ~Timer();
47 
48   void Dump();
49 
50   static void SetDisplayDepth(uint32_t depth);
51 
52   static void SetQuiet(bool value);
53 
54   static void DumpCategoryTimes(Stream *s);
55 
56   static void ResetCategoryTimes();
57 
58 protected:
59   using TimePoint = std::chrono::steady_clock::time_point;
60   void ChildDuration(TimePoint::duration dur) { m_child_duration += dur; }
61 
62   Category &m_category;
63   TimePoint m_total_start;
64   TimePoint::duration m_child_duration{0};
65 
66   static std::atomic<bool> g_quiet;
67   static std::atomic<unsigned> g_display_depth;
68 
69 private:
70   Timer(const Timer &) = delete;
71   const Timer &operator=(const Timer &) = delete;
72 };
73 
74 } // namespace lldb_private
75 
76 #endif // LLDB_UTILITY_TIMER_H
77