xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Support/TimeProfiler.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- llvm/Support/TimeProfiler.h - Hierarchical Time Profiler -*- 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 // This provides lightweight and dependency-free machinery to trace execution
10 // time around arbitrary code. Two API flavors are available.
11 //
12 // The primary API uses a RAII object to trigger tracing:
13 //
14 // \code
15 //   {
16 //     TimeTraceScope scope("my_event_name");
17 //     ...my code...
18 //   }
19 // \endcode
20 //
21 // If the code to be profiled does not have a natural lexical scope then
22 // it is also possible to start and end events with respect to an implicit
23 // per-thread stack of profiling entries:
24 //
25 // \code
26 //   timeTraceProfilerBegin("my_event_name");
27 //   ...my code...
28 //   timeTraceProfilerEnd();  // must be called on all control flow paths
29 // \endcode
30 //
31 // Time profiling entries can be given an arbitrary name and, optionally,
32 // an arbitrary 'detail' string. The resulting trace will include 'Total'
33 // entries summing the time spent for each name. Thus, it's best to choose
34 // names to be fairly generic, and rely on the detail field to capture
35 // everything else of interest.
36 //
37 // To avoid lifetime issues name and detail strings are copied into the event
38 // entries at their time of creation. Care should be taken to make string
39 // construction cheap to prevent 'Heisenperf' effects. In particular, the
40 // 'detail' argument may be a string-returning closure:
41 //
42 // \code
43 //   int n;
44 //   {
45 //     TimeTraceScope scope("my_event_name",
46 //                          [n]() { return (Twine("x=") + Twine(n)).str(); });
47 //     ...my code...
48 //   }
49 // \endcode
50 // The closure will not be called if tracing is disabled. Otherwise, the
51 // resulting string will be directly moved into the entry.
52 //
53 // The main process should begin with a timeTraceProfilerInitialize, and
54 // finish with timeTraceProfileWrite and timeTraceProfilerCleanup calls.
55 // Each new thread should begin with a timeTraceProfilerInitialize, and
56 // finish with a timeTraceProfilerFinishThread call.
57 //
58 // Timestamps come from std::chrono::stable_clock. Note that threads need
59 // not see the same time from that clock, and the resolution may not be
60 // the best available.
61 //
62 // Currently, there are a number of compatible viewers:
63 //  - chrome://tracing is the original chromium trace viewer.
64 //  - http://ui.perfetto.dev is the replacement for the above, under active
65 //    development by Google as part of the 'Perfetto' project.
66 //  - https://www.speedscope.app/ has also been reported as an option.
67 //
68 // Future work:
69 //  - Support akin to LLVM_DEBUG for runtime enable/disable of named tracing
70 //    families for non-debug builds which wish to support optional tracing.
71 //  - Evaluate the detail closures at profile write time to avoid
72 //    stringification costs interfering with tracing.
73 //
74 //===----------------------------------------------------------------------===//
75 
76 #ifndef LLVM_SUPPORT_TIMEPROFILER_H
77 #define LLVM_SUPPORT_TIMEPROFILER_H
78 
79 #include "llvm/ADT/STLFunctionalExtras.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Error.h"
82 
83 namespace llvm {
84 
85 class raw_pwrite_stream;
86 
87 // Type of the time trace event.
88 enum class TimeTraceEventType {
89   // Complete events have a duration (start and end time points) and are marked
90   // by the "X" phase type.
91   CompleteEvent,
92   // Instant events don't have a duration, they happen at an instant in time.
93   // They are marked with "i" phase type. The field End is ignored for them.
94   InstantEvent,
95   // Async events mark asynchronous operations and are specified by the "b"
96   // (start) and "e" (end) phase types.
97   AsyncEvent
98 };
99 
100 struct TimeTraceMetadata {
101   std::string Detail;
102   // Source file and line number information for the event.
103   std::string File;
104   int Line = 0;
105 
isEmptyTimeTraceMetadata106   bool isEmpty() const { return Detail.empty() && File.empty(); }
107 };
108 
109 struct TimeTraceProfiler;
110 LLVM_ABI TimeTraceProfiler *getTimeTraceProfilerInstance();
111 
112 LLVM_ABI bool isTimeTraceVerbose();
113 
114 struct TimeTraceProfilerEntry;
115 
116 /// Initialize the time trace profiler.
117 /// This sets up the global \p TimeTraceProfilerInstance
118 /// variable to be the profiler instance.
119 LLVM_ABI void timeTraceProfilerInitialize(unsigned TimeTraceGranularity,
120                                           StringRef ProcName,
121                                           bool TimeTraceVerbose = false);
122 
123 /// Cleanup the time trace profiler, if it was initialized.
124 LLVM_ABI void timeTraceProfilerCleanup();
125 
126 /// Finish a time trace profiler running on a worker thread.
127 LLVM_ABI void timeTraceProfilerFinishThread();
128 
129 /// Is the time trace profiler enabled, i.e. initialized?
timeTraceProfilerEnabled()130 inline bool timeTraceProfilerEnabled() {
131   return getTimeTraceProfilerInstance() != nullptr;
132 }
133 
134 /// Write profiling data to output stream.
135 /// Data produced is JSON, in Chrome "Trace Event" format, see
136 /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
137 LLVM_ABI void timeTraceProfilerWrite(raw_pwrite_stream &OS);
138 
139 /// Write profiling data to a file.
140 /// The function will write to \p PreferredFileName if provided, if not
141 /// then will write to \p FallbackFileName appending .time-trace.
142 /// Returns a StringError indicating a failure if the function is
143 /// unable to open the file for writing.
144 LLVM_ABI Error timeTraceProfilerWrite(StringRef PreferredFileName,
145                                       StringRef FallbackFileName);
146 
147 /// Manually begin a time section, with the given \p Name and \p Detail.
148 /// Profiler copies the string data, so the pointers can be given into
149 /// temporaries. Time sections can be hierarchical; every Begin must have a
150 /// matching End pair but they can nest.
151 LLVM_ABI TimeTraceProfilerEntry *timeTraceProfilerBegin(StringRef Name,
152                                                         StringRef Detail);
153 LLVM_ABI TimeTraceProfilerEntry *
154 timeTraceProfilerBegin(StringRef Name,
155                        llvm::function_ref<std::string()> Detail);
156 
157 LLVM_ABI TimeTraceProfilerEntry *
158 timeTraceProfilerBegin(StringRef Name,
159                        llvm::function_ref<TimeTraceMetadata()> MetaData);
160 
161 /// Manually begin a time section, with the given \p Name and \p Detail.
162 /// This starts Async Events having \p Name as a category which is shown
163 /// separately from other traces. See
164 /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.jh64i9l3vwa1
165 /// for more details.
166 LLVM_ABI TimeTraceProfilerEntry *timeTraceAsyncProfilerBegin(StringRef Name,
167                                                              StringRef Detail);
168 
169 // Mark an instant event.
170 LLVM_ABI void
171 timeTraceAddInstantEvent(StringRef Name,
172                          llvm::function_ref<std::string()> Detail);
173 
174 /// Manually end the last time section.
175 LLVM_ABI void timeTraceProfilerEnd();
176 LLVM_ABI void timeTraceProfilerEnd(TimeTraceProfilerEntry *E);
177 
178 /// The TimeTraceScope is a helper class to call the begin and end functions
179 /// of the time trace profiler.  When the object is constructed, it begins
180 /// the section; and when it is destroyed, it stops it. If the time profiler
181 /// is not initialized, the overhead is a single branch.
182 class TimeTraceScope {
183 public:
184   TimeTraceScope() = delete;
185   TimeTraceScope(const TimeTraceScope &) = delete;
186   TimeTraceScope &operator=(const TimeTraceScope &) = delete;
187   TimeTraceScope(TimeTraceScope &&) = delete;
188   TimeTraceScope &operator=(TimeTraceScope &&) = delete;
189 
TimeTraceScope(StringRef Name)190   TimeTraceScope(StringRef Name)
191       : Entry(timeTraceProfilerBegin(Name, StringRef())) {}
TimeTraceScope(StringRef Name,StringRef Detail)192   TimeTraceScope(StringRef Name, StringRef Detail)
193       : Entry(timeTraceProfilerBegin(Name, Detail)) {}
TimeTraceScope(StringRef Name,llvm::function_ref<std::string ()> Detail)194   TimeTraceScope(StringRef Name, llvm::function_ref<std::string()> Detail)
195       : Entry(timeTraceProfilerBegin(Name, Detail)) {}
TimeTraceScope(StringRef Name,llvm::function_ref<TimeTraceMetadata ()> Metadata)196   TimeTraceScope(StringRef Name,
197                  llvm::function_ref<TimeTraceMetadata()> Metadata)
198       : Entry(timeTraceProfilerBegin(Name, Metadata)) {}
~TimeTraceScope()199   ~TimeTraceScope() {
200     if (Entry)
201       timeTraceProfilerEnd(Entry);
202   }
203 
204 private:
205   TimeTraceProfilerEntry *Entry = nullptr;
206 };
207 
208 } // end namespace llvm
209 
210 #endif
211