LLVM 20.0.0git
TimeProfiler.cpp
Go to the documentation of this file.
1//===-- TimeProfiler.cpp - Hierarchical Time Profiler ---------------------===//
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 file implements hierarchical time profiler.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/Support/JSON.h"
18#include "llvm/Support/Path.h"
21#include <algorithm>
22#include <cassert>
23#include <chrono>
24#include <memory>
25#include <mutex>
26#include <string>
27#include <vector>
28
29using namespace llvm;
30
31namespace {
32
33using std::chrono::duration;
34using std::chrono::duration_cast;
35using std::chrono::microseconds;
36using std::chrono::steady_clock;
38using std::chrono::time_point;
39using std::chrono::time_point_cast;
40
41struct TimeTraceProfilerInstances {
42 std::mutex Lock;
43 std::vector<TimeTraceProfiler *> List;
44};
45
46TimeTraceProfilerInstances &getTimeTraceProfilerInstances() {
47 static TimeTraceProfilerInstances Instances;
48 return Instances;
49}
50
51} // anonymous namespace
52
53// Per Thread instance
55
58}
59
60namespace {
61
62using ClockType = steady_clock;
63using TimePointType = time_point<ClockType>;
64using DurationType = duration<ClockType::rep, ClockType::period>;
65using CountAndDurationType = std::pair<size_t, DurationType>;
66using NameAndCountAndDurationType =
67 std::pair<std::string, CountAndDurationType>;
68
69} // anonymous namespace
70
71/// Represents an open or completed time section entry to be captured.
73 const TimePointType Start;
74 TimePointType End;
75 const std::string Name;
77
78 const bool AsyncEvent = false;
79 TimeTraceProfilerEntry(TimePointType &&S, TimePointType &&E, std::string &&N,
80 std::string &&Dt, bool Ae)
81 : Start(std::move(S)), End(std::move(E)), Name(std::move(N)), Metadata(),
82 AsyncEvent(Ae) {
83 Metadata.Detail = std::move(Dt);
84 }
85
86 TimeTraceProfilerEntry(TimePointType &&S, TimePointType &&E, std::string &&N,
87 TimeTraceMetadata &&Mt, bool Ae)
88 : Start(std::move(S)), End(std::move(E)), Name(std::move(N)),
89 Metadata(std::move(Mt)), AsyncEvent(Ae) {}
90
91 // Calculate timings for FlameGraph. Cast time points to microsecond precision
92 // rather than casting duration. This avoids truncation issues causing inner
93 // scopes overruning outer scopes.
94 ClockType::rep getFlameGraphStartUs(TimePointType StartTime) const {
95 return (time_point_cast<microseconds>(Start) -
96 time_point_cast<microseconds>(StartTime))
97 .count();
98 }
99
100 ClockType::rep getFlameGraphDurUs() const {
101 return (time_point_cast<microseconds>(End) -
102 time_point_cast<microseconds>(Start))
103 .count();
104 }
105};
106
109 bool TimeTraceVerbose = false)
110 : BeginningOfTime(system_clock::now()), StartTime(ClockType::now()),
111 ProcName(ProcName), Pid(sys::Process::getProcessId()),
115 }
116
118 llvm::function_ref<std::string()> Detail,
119 bool AsyncEvent = false) {
120 Stack.emplace_back(std::make_unique<TimeTraceProfilerEntry>(
121 ClockType::now(), TimePointType(), std::move(Name), Detail(),
122 AsyncEvent));
123 return Stack.back().get();
124 }
125
128 bool AsyncEvent = false) {
129 Stack.emplace_back(std::make_unique<TimeTraceProfilerEntry>(
130 ClockType::now(), TimePointType(), std::move(Name), Metadata(),
131 AsyncEvent));
132 return Stack.back().get();
133 }
134
135 void end() {
136 assert(!Stack.empty() && "Must call begin() first");
137 end(*Stack.back());
138 }
139
141 assert(!Stack.empty() && "Must call begin() first");
142 E.End = ClockType::now();
143
144 // Calculate duration at full precision for overall counts.
145 DurationType Duration = E.End - E.Start;
146
147 // Only include sections longer or equal to TimeTraceGranularity msec.
148 if (duration_cast<microseconds>(Duration).count() >= TimeTraceGranularity)
149 Entries.emplace_back(E);
150
151 // Track total time taken by each "name", but only the topmost levels of
152 // them; e.g. if there's a template instantiation that instantiates other
153 // templates from within, we only want to add the topmost one. "topmost"
154 // happens to be the ones that don't have any currently open entries above
155 // itself.
157 [&](const std::unique_ptr<TimeTraceProfilerEntry> &Val) {
158 return Val->Name == E.Name;
159 })) {
160 auto &CountAndTotal = CountAndTotalPerName[E.Name];
161 CountAndTotal.first++;
162 CountAndTotal.second += Duration;
163 };
164
166 [&](const std::unique_ptr<TimeTraceProfilerEntry> &Val) {
167 return Val.get() == &E;
168 });
169 }
170
171 // Write events from this TimeTraceProfilerInstance and
172 // ThreadTimeTraceProfilerInstances.
174 // Acquire Mutex as reading ThreadTimeTraceProfilerInstances.
175 auto &Instances = getTimeTraceProfilerInstances();
176 std::lock_guard<std::mutex> Lock(Instances.Lock);
177 assert(Stack.empty() &&
178 "All profiler sections should be ended when calling write");
179 assert(llvm::all_of(Instances.List,
180 [](const auto &TTP) { return TTP->Stack.empty(); }) &&
181 "All profiler sections should be ended when calling write");
182
183 json::OStream J(OS);
184 J.objectBegin();
185 J.attributeBegin("traceEvents");
186 J.arrayBegin();
187
188 // Emit all events for the main flame graph.
189 auto writeEvent = [&](const auto &E, uint64_t Tid) {
190 auto StartUs = E.getFlameGraphStartUs(StartTime);
191 auto DurUs = E.getFlameGraphDurUs();
192
193 J.object([&] {
194 J.attribute("pid", Pid);
195 J.attribute("tid", int64_t(Tid));
196 J.attribute("ts", StartUs);
197 if (E.AsyncEvent) {
198 J.attribute("cat", E.Name);
199 J.attribute("ph", "b");
200 J.attribute("id", 0);
201 } else {
202 J.attribute("ph", "X");
203 J.attribute("dur", DurUs);
204 }
205 J.attribute("name", E.Name);
206 if (!E.Metadata.isEmpty()) {
207 J.attributeObject("args", [&] {
208 if (!E.Metadata.Detail.empty())
209 J.attribute("detail", E.Metadata.Detail);
210 if (!E.Metadata.File.empty())
211 J.attribute("file", E.Metadata.File);
212 if (E.Metadata.Line > 0)
213 J.attribute("line", E.Metadata.Line);
214 });
215 }
216 });
217
218 if (E.AsyncEvent) {
219 J.object([&] {
220 J.attribute("pid", Pid);
221 J.attribute("tid", int64_t(Tid));
222 J.attribute("ts", StartUs + DurUs);
223 J.attribute("cat", E.Name);
224 J.attribute("ph", "e");
225 J.attribute("id", 0);
226 J.attribute("name", E.Name);
227 });
228 }
229 };
230 for (const TimeTraceProfilerEntry &E : Entries)
231 writeEvent(E, this->Tid);
232 for (const TimeTraceProfiler *TTP : Instances.List)
233 for (const TimeTraceProfilerEntry &E : TTP->Entries)
234 writeEvent(E, TTP->Tid);
235
236 // Emit totals by section name as additional "thread" events, sorted from
237 // longest one.
238 // Find highest used thread id.
239 uint64_t MaxTid = this->Tid;
240 for (const TimeTraceProfiler *TTP : Instances.List)
241 MaxTid = std::max(MaxTid, TTP->Tid);
242
243 // Combine all CountAndTotalPerName from threads into one.
244 StringMap<CountAndDurationType> AllCountAndTotalPerName;
245 auto combineStat = [&](const auto &Stat) {
246 StringRef Key = Stat.getKey();
247 auto Value = Stat.getValue();
248 auto &CountAndTotal = AllCountAndTotalPerName[Key];
249 CountAndTotal.first += Value.first;
250 CountAndTotal.second += Value.second;
251 };
252 for (const auto &Stat : CountAndTotalPerName)
253 combineStat(Stat);
254 for (const TimeTraceProfiler *TTP : Instances.List)
255 for (const auto &Stat : TTP->CountAndTotalPerName)
256 combineStat(Stat);
257
258 std::vector<NameAndCountAndDurationType> SortedTotals;
259 SortedTotals.reserve(AllCountAndTotalPerName.size());
260 for (const auto &Total : AllCountAndTotalPerName)
261 SortedTotals.emplace_back(std::string(Total.getKey()), Total.getValue());
262
263 llvm::sort(SortedTotals, [](const NameAndCountAndDurationType &A,
264 const NameAndCountAndDurationType &B) {
265 return A.second.second > B.second.second;
266 });
267
268 // Report totals on separate threads of tracing file.
269 uint64_t TotalTid = MaxTid + 1;
270 for (const NameAndCountAndDurationType &Total : SortedTotals) {
271 auto DurUs = duration_cast<microseconds>(Total.second.second).count();
272 auto Count = AllCountAndTotalPerName[Total.first].first;
273
274 J.object([&] {
275 J.attribute("pid", Pid);
276 J.attribute("tid", int64_t(TotalTid));
277 J.attribute("ph", "X");
278 J.attribute("ts", 0);
279 J.attribute("dur", DurUs);
280 J.attribute("name", "Total " + Total.first);
281 J.attributeObject("args", [&] {
282 J.attribute("count", int64_t(Count));
283 J.attribute("avg ms", int64_t(DurUs / Count / 1000));
284 });
285 });
286
287 ++TotalTid;
288 }
289
290 auto writeMetadataEvent = [&](const char *Name, uint64_t Tid,
291 StringRef arg) {
292 J.object([&] {
293 J.attribute("cat", "");
294 J.attribute("pid", Pid);
295 J.attribute("tid", int64_t(Tid));
296 J.attribute("ts", 0);
297 J.attribute("ph", "M");
298 J.attribute("name", Name);
299 J.attributeObject("args", [&] { J.attribute("name", arg); });
300 });
301 };
302
303 writeMetadataEvent("process_name", Tid, ProcName);
304 writeMetadataEvent("thread_name", Tid, ThreadName);
305 for (const TimeTraceProfiler *TTP : Instances.List)
306 writeMetadataEvent("thread_name", TTP->Tid, TTP->ThreadName);
307
308 J.arrayEnd();
309 J.attributeEnd();
310
311 // Emit the absolute time when this TimeProfiler started.
312 // This can be used to combine the profiling data from
313 // multiple processes and preserve actual time intervals.
314 J.attribute("beginningOfTime",
315 time_point_cast<microseconds>(BeginningOfTime)
316 .time_since_epoch()
317 .count());
318
319 J.objectEnd();
320 }
321
325 // System clock time when the session was begun.
326 const time_point<system_clock> BeginningOfTime;
327 // Profiling clock time when the session was begun.
328 const TimePointType StartTime;
329 const std::string ProcName;
333
334 // Minimum time granularity (in microseconds)
335 const unsigned TimeTraceGranularity;
336
337 // Make time trace capture verbose event details (e.g. source filenames). This
338 // can increase the size of the output by 2-3 times.
340};
341
345}
346
347void llvm::timeTraceProfilerInitialize(unsigned TimeTraceGranularity,
348 StringRef ProcName,
349 bool TimeTraceVerbose) {
351 "Profiler should not be initialized");
353 TimeTraceGranularity, llvm::sys::path::filename(ProcName),
354 TimeTraceVerbose);
355}
356
357// Removes all TimeTraceProfilerInstances.
358// Called from main thread.
362
363 auto &Instances = getTimeTraceProfilerInstances();
364 std::lock_guard<std::mutex> Lock(Instances.Lock);
365 for (auto *TTP : Instances.List)
366 delete TTP;
367 Instances.List.clear();
368}
369
370// Finish TimeTraceProfilerInstance on a worker thread.
371// This doesn't remove the instance, just moves the pointer to global vector.
373 auto &Instances = getTimeTraceProfilerInstances();
374 std::lock_guard<std::mutex> Lock(Instances.Lock);
375 Instances.List.push_back(TimeTraceProfilerInstance);
377}
378
381 "Profiler object can't be null");
383}
384
386 StringRef FallbackFileName) {
388 "Profiler object can't be null");
389
390 std::string Path = PreferredFileName.str();
391 if (Path.empty()) {
392 Path = FallbackFileName == "-" ? "out" : FallbackFileName.str();
393 Path += ".time-trace";
394 }
395
396 std::error_code EC;
398 if (EC)
399 return createStringError(EC, "Could not open " + Path);
400
402 return Error::success();
403}
404
406 StringRef Detail) {
407 if (TimeTraceProfilerInstance != nullptr)
409 std::string(Name), [&]() { return std::string(Detail); }, false);
410 return nullptr;
411}
412
415 llvm::function_ref<std::string()> Detail) {
416 if (TimeTraceProfilerInstance != nullptr)
417 return TimeTraceProfilerInstance->begin(std::string(Name), Detail, false);
418 return nullptr;
419}
420
424 if (TimeTraceProfilerInstance != nullptr)
425 return TimeTraceProfilerInstance->begin(std::string(Name), Metadata, false);
426 return nullptr;
427}
428
430 StringRef Detail) {
431 if (TimeTraceProfilerInstance != nullptr)
433 std::string(Name), [&]() { return std::string(Detail); }, true);
434 return nullptr;
435}
436
438 if (TimeTraceProfilerInstance != nullptr)
440}
441
443 if (TimeTraceProfilerInstance != nullptr)
445}
This file defines the StringMap class.
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_THREAD_LOCAL
\macro LLVM_THREAD_LOCAL A thread-local storage specifier which can be used with globals,...
Definition: Compiler.h:577
std::string Name
This file supports working with JSON data.
if(VerifyEach)
Provides a library for accessing information about this process and other processes on the operating ...
const NodeList & List
Definition: RDFGraph.cpp:201
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
static LLVM_THREAD_LOCAL TimeTraceProfiler * TimeTraceProfilerInstance
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Root of the metadata hierarchy.
Definition: Metadata.h:62
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
unsigned size() const
Definition: StringMap.h:104
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:215
LLVM Value Representation.
Definition: Value.h:74
An efficient, type-erasing, non-owning reference to a callable.
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition: JSON.h:979
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
Definition: JSON.h:1009
void attributeObject(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an object with attributes from the Block.
Definition: JSON.h:1042
void attributeBegin(llvm::StringRef Key)
Definition: JSON.cpp:878
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
Definition: JSON.h:1034
void arrayBegin()
Definition: JSON.cpp:840
void objectBegin()
Definition: JSON.cpp:859
void attributeEnd()
Definition: JSON.cpp:898
void objectEnd()
Definition: JSON.cpp:867
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:434
A collection of legacy interfaces for querying information about the current executing process.
Definition: Process.h:43
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:767
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
TimeTraceProfiler * getTimeTraceProfilerInstance()
void timeTraceProfilerInitialize(unsigned TimeTraceGranularity, StringRef ProcName, bool TimeTraceVerbose=false)
Initialize the time trace profiler.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
void timeTraceProfilerFinishThread()
Finish a time trace profiler running on a worker thread.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1736
void timeTraceProfilerEnd()
Manually end the last time section.
void get_thread_name(SmallVectorImpl< char > &Name)
Get the name of the current thread.
Definition: Threading.cpp:39
TimeTraceProfilerEntry * timeTraceAsyncProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
bool isTimeTraceVerbose()
uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
Definition: Threading.cpp:33
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1914
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
void timeTraceProfilerCleanup()
Cleanup the time trace profiler, if it was initialized.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2051
void timeTraceProfilerWrite(raw_pwrite_stream &OS)
Write profiling data to output stream.
TimeTraceProfilerEntry * timeTraceProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
Represents an open or completed time section entry to be captured.
const TimePointType Start
ClockType::rep getFlameGraphDurUs() const
TimeTraceProfilerEntry(TimePointType &&S, TimePointType &&E, std::string &&N, std::string &&Dt, bool Ae)
ClockType::rep getFlameGraphStartUs(TimePointType StartTime) const
TimeTraceMetadata Metadata
TimeTraceProfilerEntry(TimePointType &&S, TimePointType &&E, std::string &&N, TimeTraceMetadata &&Mt, bool Ae)
const sys::Process::Pid Pid
void write(raw_pwrite_stream &OS)
StringMap< CountAndDurationType > CountAndTotalPerName
TimeTraceProfilerEntry * begin(std::string Name, llvm::function_ref< TimeTraceMetadata()> Metadata, bool AsyncEvent=false)
const unsigned TimeTraceGranularity
TimeTraceProfilerEntry * begin(std::string Name, llvm::function_ref< std::string()> Detail, bool AsyncEvent=false)
const time_point< system_clock > BeginningOfTime
TimeTraceProfiler(unsigned TimeTraceGranularity=0, StringRef ProcName="", bool TimeTraceVerbose=false)
SmallVector< std::unique_ptr< TimeTraceProfilerEntry >, 16 > Stack
SmallString< 0 > ThreadName
const std::string ProcName
SmallVector< TimeTraceProfilerEntry, 128 > Entries
const TimePointType StartTime
void end(TimeTraceProfilerEntry &E)