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 <string>
8 
9 #include <hilti/rt/configuration.h>
10 #include <hilti/rt/global-state.h>
11 #include <hilti/rt/profiler-state.h>
12 #include <hilti/rt/types/null.h>
13 #include <hilti/rt/types/optional.h>
14 
15 namespace hilti::rt {
16 
17 class Profiler;
18 
19 namespace profiler {
20 
21 hilti::rt::Optional<Profiler> start(std::string_view name, hilti::rt::Optional<uint64_t> volume = Null());
23 
24 namespace detail {
25 
26 // Internal initialization function, called from library's `init()` when
27 // profiling has been requested.
28 extern void init();
29 
30 // Internal shutdown function, called from library's `done()`. Produces a final
31 // profiling report.
32 extern void done();
33 
34 } // namespace detail
35 } // namespace profiler
36 
46 class Profiler {
47 public:
53  Profiler() = default;
54 
55  Profiler(const Profiler& other) = delete;
56  Profiler(Profiler&& other) = default;
57 
60 
61  Profiler& operator=(const Profiler& other) = delete;
62  Profiler& operator=(Profiler&& other) = default;
63 
65  void record(const profiler::Measurement& end);
66 
68  operator bool() const { return ! _name.empty(); }
69 
76 
77 protected:
85  Profiler(std::string_view name, hilti::rt::Optional<uint64_t> volume) : _name(name), _start(snapshot(volume)) {
86  _register();
87  }
88 
89 private:
90  friend hilti::rt::Optional<Profiler> profiler::start(std::string_view name, hilti::rt::Optional<uint64_t> volume);
91  friend void profiler::detail::done();
92 
93  void _register() const;
94 
95  std::string _name; // Name of block to profile; empty is not active.
96  profiler::Measurement _start; // Initial measurement at construction time.
97 };
98 
99 namespace profiler {
109 inline hilti::rt::Optional<Profiler> start(std::string_view name, hilti::rt::Optional<uint64_t> volume) {
110  if ( ::hilti::rt::detail::unsafeGlobalState()->profiling_enabled )
111  return Profiler(name, volume);
112  else
113  return {};
114 }
115 
124  if ( p )
125  p->record(Profiler::snapshot(volume));
126 }
127 
135 hilti::rt::Optional<Measurement> get(const std::string& name);
136 
138 extern void report();
139 
140 } // namespace profiler
141 } // namespace hilti::rt
Definition: optional.h:33
Definition: profiler.h:46
Profiler(std::string_view name, hilti::rt::Optional< uint64_t > volume)
Definition: profiler.h:85
void record(const profiler::Measurement &end)
Definition: profiler.cc:48
~Profiler()
Definition: profiler.h:59
static profiler::Measurement snapshot(hilti::rt::Optional< uint64_t > volume=Null())
Definition: profiler.cc:38
Definition: any.h:7
void done()
Definition: init.cc:64
void init()
Definition: init.cc:21
Definition: null.h:20
Definition: profiler-state.h:22