blob: ca9119e30b65f783bf6b587cda9c53e57b182e65 [file] [log] [blame]
Anton Afanasyevd880de22019-03-30 08:42:48 +00001//===-- TimeProfiler.cpp - Hierarchical Time Profiler ---------------------===//
2//
Anton Afanasyev26536722019-04-15 21:02:47 +00003// 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
Anton Afanasyevd880de22019-03-30 08:42:48 +00006//
7//===----------------------------------------------------------------------===//
8//
Anton Afanasyev26536722019-04-15 21:02:47 +00009// This file implements hierarchical time profiler.
Anton Afanasyevd880de22019-03-30 08:42:48 +000010//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/TimeProfiler.h"
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +000014#include "llvm/ADT/StringMap.h"
Anton Afanasyev26536722019-04-15 21:02:47 +000015#include "llvm/Support/CommandLine.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000016#include "llvm/Support/FileSystem.h"
Anton Afanasyev6547d512019-04-16 06:35:07 +000017#include "llvm/Support/JSON.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000018#include <cassert>
19#include <chrono>
20#include <string>
Anton Afanasyevd880de22019-03-30 08:42:48 +000021#include <vector>
22
23using namespace std::chrono;
24
25namespace llvm {
26
27TimeTraceProfiler *TimeTraceProfilerInstance = nullptr;
28
Anton Afanasyevd880de22019-03-30 08:42:48 +000029typedef duration<steady_clock::rep, steady_clock::period> DurationType;
Russell Gallopc6fda602019-09-05 09:26:04 +000030typedef time_point<steady_clock> TimePointType;
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +000031typedef std::pair<size_t, DurationType> CountAndDurationType;
32typedef std::pair<std::string, CountAndDurationType>
33 NameAndCountAndDurationType;
Anton Afanasyevd880de22019-03-30 08:42:48 +000034
35struct Entry {
Russell Gallopc6fda602019-09-05 09:26:04 +000036 TimePointType Start;
37 TimePointType End;
Anton Afanasyevd880de22019-03-30 08:42:48 +000038 std::string Name;
39 std::string Detail;
Anton Afanasyev26536722019-04-15 21:02:47 +000040
Russell Gallopc6fda602019-09-05 09:26:04 +000041 Entry(TimePointType &&S, TimePointType &&E, std::string &&N, std::string &&Dt)
42 : Start(std::move(S)), End(std::move(E)), Name(std::move(N)),
Anton Afanasyev26536722019-04-15 21:02:47 +000043 Detail(std::move(Dt)){};
Russell Gallopc6fda602019-09-05 09:26:04 +000044
45 // Calculate timings for FlameGraph. Cast time points to microsecond precision
46 // rather than casting duration. This avoid truncation issues causing inner
47 // scopes overruning outer scopes.
48 steady_clock::rep getFlameGraphStartUs(TimePointType StartTime) const {
49 return (time_point_cast<microseconds>(Start) -
50 time_point_cast<microseconds>(StartTime))
51 .count();
52 }
53
54 steady_clock::rep getFlameGraphDurUs() const {
55 return (time_point_cast<microseconds>(End) -
56 time_point_cast<microseconds>(Start))
57 .count();
58 }
Anton Afanasyevd880de22019-03-30 08:42:48 +000059};
60
61struct TimeTraceProfiler {
62 TimeTraceProfiler() {
Anton Afanasyevd880de22019-03-30 08:42:48 +000063 StartTime = steady_clock::now();
64 }
65
66 void begin(std::string Name, llvm::function_ref<std::string()> Detail) {
Russell Gallopc6fda602019-09-05 09:26:04 +000067 Stack.emplace_back(steady_clock::now(), TimePointType(), std::move(Name),
Anton Afanasyev26536722019-04-15 21:02:47 +000068 Detail());
Anton Afanasyevd880de22019-03-30 08:42:48 +000069 }
70
71 void end() {
72 assert(!Stack.empty() && "Must call begin() first");
73 auto &E = Stack.back();
Russell Gallopc6fda602019-09-05 09:26:04 +000074 E.End = steady_clock::now();
75
76 // Check that end times monotonically increase.
77 assert((Entries.empty() ||
78 (E.getFlameGraphStartUs(StartTime) + E.getFlameGraphDurUs() >=
79 Entries.back().getFlameGraphStartUs(StartTime) +
80 Entries.back().getFlameGraphDurUs())) &&
81 "TimeProfiler scope ended earlier than previous scope");
82
83 // Calculate duration at full precision for overall counts.
84 DurationType Duration = E.End - E.Start;
Anton Afanasyevd880de22019-03-30 08:42:48 +000085
Anton Afanasyev3f3a2572019-08-19 22:58:26 +000086 // Only include sections longer or equal to TimeTraceGranularity msec.
Russell Gallopc6fda602019-09-05 09:26:04 +000087 if (duration_cast<microseconds>(Duration).count() >= TimeTraceGranularity)
Anton Afanasyevd880de22019-03-30 08:42:48 +000088 Entries.emplace_back(E);
89
90 // Track total time taken by each "name", but only the topmost levels of
91 // them; e.g. if there's a template instantiation that instantiates other
92 // templates from within, we only want to add the topmost one. "topmost"
93 // happens to be the ones that don't have any currently open entries above
94 // itself.
95 if (std::find_if(++Stack.rbegin(), Stack.rend(), [&](const Entry &Val) {
96 return Val.Name == E.Name;
97 }) == Stack.rend()) {
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +000098 auto &CountAndTotal = CountAndTotalPerName[E.Name];
99 CountAndTotal.first++;
Russell Gallopc6fda602019-09-05 09:26:04 +0000100 CountAndTotal.second += Duration;
Anton Afanasyevd880de22019-03-30 08:42:48 +0000101 }
102
103 Stack.pop_back();
104 }
105
Anton Afanasyev26536722019-04-15 21:02:47 +0000106 void Write(raw_pwrite_stream &OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +0000107 assert(Stack.empty() &&
108 "All profiler sections should be ended when calling Write");
Sam McCalla7edcfb2019-04-25 12:51:42 +0000109 json::OStream J(OS);
110 J.objectBegin();
111 J.attributeBegin("traceEvents");
112 J.arrayBegin();
Anton Afanasyevd880de22019-03-30 08:42:48 +0000113
114 // Emit all events for the main flame graph.
115 for (const auto &E : Entries) {
Russell Gallopc6fda602019-09-05 09:26:04 +0000116 auto StartUs = E.getFlameGraphStartUs(StartTime);
117 auto DurUs = E.getFlameGraphDurUs();
Anton Afanasyev6547d512019-04-16 06:35:07 +0000118
Sam McCalla7edcfb2019-04-25 12:51:42 +0000119 J.object([&]{
120 J.attribute("pid", 1);
121 J.attribute("tid", 0);
122 J.attribute("ph", "X");
123 J.attribute("ts", StartUs);
124 J.attribute("dur", DurUs);
125 J.attribute("name", E.Name);
126 J.attributeObject("args", [&] { J.attribute("detail", E.Detail); });
Anton Afanasyev6547d512019-04-16 06:35:07 +0000127 });
Anton Afanasyevd880de22019-03-30 08:42:48 +0000128 }
129
130 // Emit totals by section name as additional "thread" events, sorted from
131 // longest one.
132 int Tid = 1;
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +0000133 std::vector<NameAndCountAndDurationType> SortedTotals;
134 SortedTotals.reserve(CountAndTotalPerName.size());
Anton Afanasyev26536722019-04-15 21:02:47 +0000135 for (const auto &E : CountAndTotalPerName)
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +0000136 SortedTotals.emplace_back(E.getKey(), E.getValue());
Anton Afanasyev26536722019-04-15 21:02:47 +0000137
138 llvm::sort(SortedTotals.begin(), SortedTotals.end(),
139 [](const NameAndCountAndDurationType &A,
140 const NameAndCountAndDurationType &B) {
141 return A.second.second > B.second.second;
142 });
Anton Afanasyevd880de22019-03-30 08:42:48 +0000143 for (const auto &E : SortedTotals) {
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +0000144 auto DurUs = duration_cast<microseconds>(E.second.second).count();
145 auto Count = CountAndTotalPerName[E.first].first;
Anton Afanasyev6547d512019-04-16 06:35:07 +0000146
Sam McCalla7edcfb2019-04-25 12:51:42 +0000147 J.object([&]{
148 J.attribute("pid", 1);
149 J.attribute("tid", Tid);
150 J.attribute("ph", "X");
151 J.attribute("ts", 0);
152 J.attribute("dur", DurUs);
153 J.attribute("name", "Total " + E.first);
154 J.attributeObject("args", [&] {
155 J.attribute("count", int64_t(Count));
156 J.attribute("avg ms", int64_t(DurUs / Count / 1000));
157 });
Anton Afanasyev6547d512019-04-16 06:35:07 +0000158 });
159
Anton Afanasyevd880de22019-03-30 08:42:48 +0000160 ++Tid;
161 }
162
163 // Emit metadata event with process name.
Sam McCalla7edcfb2019-04-25 12:51:42 +0000164 J.object([&] {
165 J.attribute("cat", "");
166 J.attribute("pid", 1);
167 J.attribute("tid", 0);
168 J.attribute("ts", 0);
169 J.attribute("ph", "M");
170 J.attribute("name", "process_name");
171 J.attributeObject("args", [&] { J.attribute("name", "clang"); });
Anton Afanasyev6547d512019-04-16 06:35:07 +0000172 });
173
Sam McCalla7edcfb2019-04-25 12:51:42 +0000174 J.arrayEnd();
175 J.attributeEnd();
176 J.objectEnd();
Anton Afanasyevd880de22019-03-30 08:42:48 +0000177 }
178
Anton Afanasyev26536722019-04-15 21:02:47 +0000179 SmallVector<Entry, 16> Stack;
180 SmallVector<Entry, 128> Entries;
Anton Afanasyev03c3e0d2019-04-09 12:18:44 +0000181 StringMap<CountAndDurationType> CountAndTotalPerName;
Russell Gallopc6fda602019-09-05 09:26:04 +0000182 TimePointType StartTime;
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +0000183
184 // Minimum time granularity (in microseconds)
185 unsigned TimeTraceGranularity;
Anton Afanasyevd880de22019-03-30 08:42:48 +0000186};
187
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +0000188void timeTraceProfilerInitialize(unsigned TimeTraceGranularity) {
Anton Afanasyevd880de22019-03-30 08:42:48 +0000189 assert(TimeTraceProfilerInstance == nullptr &&
190 "Profiler should not be initialized");
191 TimeTraceProfilerInstance = new TimeTraceProfiler();
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +0000192 TimeTraceProfilerInstance->TimeTraceGranularity = TimeTraceGranularity;
Anton Afanasyevd880de22019-03-30 08:42:48 +0000193}
194
195void timeTraceProfilerCleanup() {
196 delete TimeTraceProfilerInstance;
197 TimeTraceProfilerInstance = nullptr;
198}
199
Anton Afanasyev26536722019-04-15 21:02:47 +0000200void timeTraceProfilerWrite(raw_pwrite_stream &OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +0000201 assert(TimeTraceProfilerInstance != nullptr &&
202 "Profiler object can't be null");
203 TimeTraceProfilerInstance->Write(OS);
204}
205
206void timeTraceProfilerBegin(StringRef Name, StringRef Detail) {
207 if (TimeTraceProfilerInstance != nullptr)
208 TimeTraceProfilerInstance->begin(Name, [&]() { return Detail; });
209}
210
211void timeTraceProfilerBegin(StringRef Name,
212 llvm::function_ref<std::string()> Detail) {
213 if (TimeTraceProfilerInstance != nullptr)
214 TimeTraceProfilerInstance->begin(Name, Detail);
215}
216
217void timeTraceProfilerEnd() {
218 if (TimeTraceProfilerInstance != nullptr)
219 TimeTraceProfilerInstance->end();
220}
221
222} // namespace llvm