Spicy
profiler.h
1 // Copyright (c) 2020-now by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <cstddef>
6 #include <cstdint>
7 #include <optional>
8 #include <string>
9 
10 #include <hilti/rt/configuration.h>
11 #include <hilti/rt/global-state.h>
12 #include <hilti/rt/profiler-state.h>
13 
14 namespace hilti::rt {
15 
16 class Profiler;
17 
18 namespace profiler {
19 
20 std::optional<Profiler> start(std::string_view name, std::optional<uint64_t> volume = std::nullopt);
21 void stop(std::optional<Profiler>& p, std::optional<uint64_t> volume = std::nullopt);
22 
23 namespace detail {
24 
25 // Internal initialization function, called from library's `init()` when
26 // profiling has been requested.
27 extern void init();
28 
29 // Internal shutdown function, called from library's `done()`. Produces a final
30 // profiling report.
31 extern void done();
32 
33 } // namespace detail
34 } // namespace profiler
35 
45 class Profiler {
46 public:
52  Profiler() = default;
53 
54  Profiler(const Profiler& other) = delete;
55  Profiler(Profiler&& other) = default;
56 
59 
60  Profiler& operator=(const Profiler& other) = delete;
61  Profiler& operator=(Profiler&& other) = default;
62 
64  void record(const profiler::Measurement& end);
65 
67  operator bool() const { return ! _name.empty(); }
68 
74  static profiler::Measurement snapshot(std::optional<uint64_t> volume = std::nullopt);
75 
76 protected:
84  Profiler(std::string_view name, std::optional<uint64_t> volume) : _name(name), _start(snapshot(volume)) {
85  _register();
86  }
87 
88 private:
89  friend std::optional<Profiler> profiler::start(std::string_view name, std::optional<uint64_t> volume);
90  friend void profiler::detail::done();
91 
92  void _register() const;
93 
94  std::string _name; // Name of block to profile; empty is not active.
95  profiler::Measurement _start; // Initial measurement at construction time.
96 };
97 
98 namespace profiler {
108 inline std::optional<Profiler> start(std::string_view name, std::optional<uint64_t> volume) {
109  if ( ::hilti::rt::detail::unsafeGlobalState()->profiling_enabled )
110  return Profiler(name, volume);
111  else
112  return {};
113 }
114 
122 inline void stop(std::optional<Profiler>& p, std::optional<uint64_t> volume) {
123  if ( p )
124  p->record(Profiler::snapshot(volume));
125 }
126 
134 std::optional<Measurement> get(const std::string& name);
135 
137 extern void report();
138 
139 } // namespace profiler
140 } // namespace hilti::rt
Definition: profiler.h:45
Profiler(std::string_view name, std::optional< uint64_t > volume)
Definition: profiler.h:84
void record(const profiler::Measurement &end)
Definition: profiler.cc:43
~Profiler()
Definition: profiler.h:58
static profiler::Measurement snapshot(std::optional< uint64_t > volume=std::nullopt)
Definition: profiler.cc:33
Definition: any.h:7
void done()
Definition: init.cc:64
void init()
Definition: init.cc:21
Definition: profiler-state.h:22