Profiler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Core/Profiler.h>
  5. #include <Jolt/Core/Color.h>
  6. #include <Jolt/Core/StringTools.h>
  7. #include <Jolt/Core/QuickSort.h>
  8. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  9. #include <fstream>
  10. JPH_SUPPRESS_WARNINGS_STD_END
  11. #ifdef JPH_PROFILE_ENABLED
  12. JPH_NAMESPACE_BEGIN
  13. //////////////////////////////////////////////////////////////////////////////////////////
  14. // Profiler
  15. //////////////////////////////////////////////////////////////////////////////////////////
  16. Profiler *Profiler::sInstance = nullptr;
  17. thread_local ProfileThread *ProfileThread::sInstance = nullptr;
  18. bool ProfileMeasurement::sOutOfSamplesReported = false;
  19. void Profiler::NextFrame()
  20. {
  21. std::lock_guard lock(mLock);
  22. if (mDump)
  23. {
  24. DumpInternal();
  25. mDump = false;
  26. }
  27. for (ProfileThread *t : mThreads)
  28. t->mCurrentSample = 0;
  29. }
  30. void Profiler::Dump(const string_view &inTag)
  31. {
  32. mDump = true;
  33. mDumpTag = inTag;
  34. }
  35. void Profiler::AddThread(ProfileThread *inThread)
  36. {
  37. std::lock_guard lock(mLock);
  38. mThreads.push_back(inThread);
  39. }
  40. void Profiler::RemoveThread(ProfileThread *inThread)
  41. {
  42. std::lock_guard lock(mLock);
  43. Array<ProfileThread *>::iterator i = find(mThreads.begin(), mThreads.end(), inThread);
  44. JPH_ASSERT(i != mThreads.end());
  45. mThreads.erase(i);
  46. }
  47. void Profiler::sAggregate(int inDepth, uint32 inColor, ProfileSample *&ioSample, const ProfileSample *inEnd, Aggregators &ioAggregators, KeyToAggregator &ioKeyToAggregator)
  48. {
  49. // Store depth
  50. ioSample->mDepth = uint8(min(255, inDepth));
  51. // Update color
  52. if (ioSample->mColor == 0)
  53. ioSample->mColor = inColor;
  54. else
  55. inColor = ioSample->mColor;
  56. // Start accumulating totals
  57. uint64 cycles_this_with_children = ioSample->mEndCycle - ioSample->mStartCycle;
  58. uint64 cycles_in_children = 0;
  59. // Loop over following samples until we find a sample that starts on or after our end
  60. ProfileSample *sample;
  61. for (sample = ioSample + 1; sample < inEnd && sample->mStartCycle < ioSample->mEndCycle; ++sample)
  62. {
  63. JPH_ASSERT(sample[-1].mStartCycle <= sample->mStartCycle);
  64. JPH_ASSERT(sample->mStartCycle >= ioSample->mStartCycle);
  65. JPH_ASSERT(sample->mEndCycle <= ioSample->mEndCycle);
  66. // This is a direct child of us, accumulate time
  67. cycles_in_children += sample->mEndCycle - sample->mStartCycle;
  68. // Recurse and skip over the children of this child
  69. sAggregate(inDepth + 1, inColor, sample, inEnd, ioAggregators, ioKeyToAggregator);
  70. }
  71. // Find the aggregator for this name / filename pair
  72. Aggregator *aggregator;
  73. KeyToAggregator::iterator aggregator_idx = ioKeyToAggregator.find(ioSample->mName);
  74. if (aggregator_idx == ioKeyToAggregator.end())
  75. {
  76. // Not found, add to map and insert in array
  77. ioKeyToAggregator.try_emplace(ioSample->mName, ioAggregators.size());
  78. ioAggregators.emplace_back(ioSample->mName);
  79. aggregator = &ioAggregators.back();
  80. }
  81. else
  82. {
  83. // Found
  84. aggregator = &ioAggregators[aggregator_idx->second];
  85. }
  86. // Add the measurement to the aggregator
  87. aggregator->AccumulateMeasurement(cycles_this_with_children, cycles_in_children);
  88. // Update ioSample to the last child of ioSample
  89. JPH_ASSERT(sample[-1].mStartCycle <= ioSample->mEndCycle);
  90. JPH_ASSERT(sample >= inEnd || sample->mStartCycle >= ioSample->mEndCycle);
  91. ioSample = sample - 1;
  92. }
  93. void Profiler::DumpInternal()
  94. {
  95. // Freeze data from threads
  96. // Note that this is not completely thread safe: As a profile sample is added mCurrentSample is incremented
  97. // but the data is not written until the sample finishes. So if we dump the profile information while
  98. // some other thread is running, we may get some garbage information from the previous frame
  99. Threads threads;
  100. for (ProfileThread *t : mThreads)
  101. threads.push_back({ t->mThreadName, t->mSamples, t->mSamples + t->mCurrentSample });
  102. // Shift all samples so that the first sample is at zero
  103. uint64 min_cycle = 0xffffffffffffffffUL;
  104. for (const ThreadSamples &t : threads)
  105. if (t.mSamplesBegin < t.mSamplesEnd)
  106. min_cycle = min(min_cycle, t.mSamplesBegin[0].mStartCycle);
  107. for (const ThreadSamples &t : threads)
  108. for (ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  109. {
  110. s->mStartCycle -= min_cycle;
  111. s->mEndCycle -= min_cycle;
  112. }
  113. // Determine tag of this profile
  114. String tag;
  115. if (mDumpTag.empty())
  116. {
  117. // Next sequence number
  118. static int number = 0;
  119. ++number;
  120. tag = ConvertToString(number);
  121. }
  122. else
  123. {
  124. // Take provided tag
  125. tag = mDumpTag;
  126. mDumpTag.clear();
  127. }
  128. // Aggregate data across threads
  129. Aggregators aggregators;
  130. KeyToAggregator key_to_aggregators;
  131. for (const ThreadSamples &t : threads)
  132. for (ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  133. sAggregate(0, Color::sGetDistinctColor(0).GetUInt32(), s, end, aggregators, key_to_aggregators);
  134. // Dump as list
  135. DumpList(tag.c_str(), aggregators);
  136. // Dump as chart
  137. DumpChart(tag.c_str(), threads, key_to_aggregators, aggregators);
  138. }
  139. static String sHTMLEncode(const char *inString)
  140. {
  141. String str(inString);
  142. StringReplace(str, "<", "&lt;");
  143. StringReplace(str, ">", "&gt;");
  144. return str;
  145. }
  146. void Profiler::DumpList(const char *inTag, const Aggregators &inAggregators)
  147. {
  148. // Open file
  149. std::ofstream f;
  150. f.open(StringFormat("profile_list_%s.html", inTag).c_str(), std::ofstream::out | std::ofstream::trunc);
  151. if (!f.is_open())
  152. return;
  153. // Write header
  154. f << R"(<!DOCTYPE html>
  155. <html>
  156. <head>
  157. <title>Profile List</title>
  158. <link rel="stylesheet" href="WebIncludes/semantic.min.css">
  159. <script type="text/javascript" src="WebIncludes/jquery-3.2.1.min.js"></script>
  160. <script type="text/javascript" src="WebIncludes/semantic.min.js"></script>
  161. <script type="text/javascript" src="WebIncludes/tablesort.js"></script>
  162. <script type="text/javascript">$(document).ready(function() { $('table').tablesort({ compare: function(a, b) { return isNaN(a) || isNaN(b)? a.localeCompare(b) : Number(a) - Number(b); } }); });</script>
  163. </head>
  164. <body class="minimal pushable">
  165. <table id="profile" class="ui sortable celled striped table">
  166. <thead>
  167. <tr>
  168. <th>Description</th>
  169. <th class="sorted descending">Total time with children (%)</th>
  170. <th>Total time (%)</th>
  171. <th>Calls</th>
  172. <th>&micro;s / call with children</th>
  173. <th>&micro;s / call</th>
  174. <th>Min. &micro;s / call</th>
  175. <th>Max. &micro;s / call</th>
  176. </tr>
  177. </thead>
  178. <tbody style="text-align: right;">
  179. )";
  180. // Get total time
  181. uint64 total_time = 0;
  182. for (const Aggregator &item : inAggregators)
  183. total_time += item.mTotalCyclesInCallWithChildren - item.mTotalCyclesInChildren;
  184. // Get cycles per second
  185. uint64 cycles_per_second = GetProcessorTicksPerSecond();
  186. // Sort the list
  187. Aggregators aggregators = inAggregators;
  188. QuickSort(aggregators.begin(), aggregators.end());
  189. // Write all aggregators
  190. for (const Aggregator &item : aggregators)
  191. {
  192. uint64 cycles_in_call_no_children = item.mTotalCyclesInCallWithChildren - item.mTotalCyclesInChildren;
  193. char str[2048];
  194. snprintf(str, sizeof(str), R"(<tr>
  195. <td style="text-align: left;">%s</td>
  196. <td>%.1f</td>
  197. <td>%.1f</td>
  198. <td>%u</td>
  199. <td>%.2f</td>
  200. <td>%.2f</td>
  201. <td>%.2f</td>
  202. <td>%.2f</td>
  203. </tr>)",
  204. sHTMLEncode(item.mName).c_str(), // Description
  205. 100.0 * item.mTotalCyclesInCallWithChildren / total_time, // Total time with children
  206. 100.0 * cycles_in_call_no_children / total_time, // Total time no children
  207. item.mCallCounter, // Calls
  208. 1000000.0 * item.mTotalCyclesInCallWithChildren / cycles_per_second / item.mCallCounter, // us / call with children
  209. 1000000.0 * cycles_in_call_no_children / cycles_per_second / item.mCallCounter, // us / call no children
  210. 1000000.0 * item.mMinCyclesInCallWithChildren / cycles_per_second, // Min. us / call with children
  211. 1000000.0 * item.mMaxCyclesInCallWithChildren / cycles_per_second); // Max. us / call with children
  212. f << str;
  213. }
  214. // End table
  215. f << R"(</tbody></table></body></html>)";
  216. }
  217. void Profiler::DumpChart(const char *inTag, const Threads &inThreads, const KeyToAggregator &inKeyToAggregators, const Aggregators &inAggregators)
  218. {
  219. // Open file
  220. std::ofstream f;
  221. f.open(StringFormat("profile_chart_%s.html", inTag).c_str(), std::ofstream::out | std::ofstream::trunc);
  222. if (!f.is_open())
  223. return;
  224. // Write header
  225. f << R"(<!DOCTYPE html>
  226. <html>
  227. <head>
  228. <title>Profile Chart</title>
  229. <link rel="stylesheet" href="WebIncludes/profile_chart.css">
  230. <script type="text/javascript" src="WebIncludes/profile_chart.js"></script>
  231. </head>
  232. <body onload="startChart();">
  233. <script type="text/javascript">
  234. )";
  235. // Get cycles per second
  236. uint64 cycles_per_second = GetProcessorTicksPerSecond();
  237. f << "var cycles_per_second = " << cycles_per_second << ";\n";
  238. // Dump samples
  239. f << "var threads = [\n";
  240. bool first_thread = true;
  241. for (const ThreadSamples &t : inThreads)
  242. {
  243. if (!first_thread)
  244. f << ",\n";
  245. first_thread = false;
  246. f << "{\nthread_name: \"" << t.mThreadName << "\",\naggregator: [";
  247. bool first = true;
  248. for (const ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  249. {
  250. if (!first)
  251. f << ",";
  252. first = false;
  253. f << inKeyToAggregators.find(s->mName)->second;
  254. }
  255. f << "],\ncolor: [";
  256. first = true;
  257. for (const ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  258. {
  259. if (!first)
  260. f << ",";
  261. first = false;
  262. Color c(s->mColor);
  263. f << StringFormat("\"#%02x%02x%02x\"", c.r, c.g, c.b);
  264. }
  265. f << "],\nstart: [";
  266. first = true;
  267. for (const ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  268. {
  269. if (!first)
  270. f << ",";
  271. first = false;
  272. f << s->mStartCycle;
  273. }
  274. f << "],\ncycles: [";
  275. first = true;
  276. for (const ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  277. {
  278. if (!first)
  279. f << ",";
  280. first = false;
  281. f << s->mEndCycle - s->mStartCycle;
  282. }
  283. f << "],\ndepth: [";
  284. first = true;
  285. for (const ProfileSample *s = t.mSamplesBegin, *end = t.mSamplesEnd; s < end; ++s)
  286. {
  287. if (!first)
  288. f << ",";
  289. first = false;
  290. f << int(s->mDepth);
  291. }
  292. f << "]\n}";
  293. }
  294. // Dump aggregated data
  295. f << "];\nvar aggregated = {\nname: [";
  296. bool first = true;
  297. for (const Aggregator &a : inAggregators)
  298. {
  299. if (!first)
  300. f << ",";
  301. first = false;
  302. String name = "\"" + sHTMLEncode(a.mName) + "\"";
  303. f << name;
  304. }
  305. f << "],\ncalls: [";
  306. first = true;
  307. for (const Aggregator &a : inAggregators)
  308. {
  309. if (!first)
  310. f << ",";
  311. first = false;
  312. f << a.mCallCounter;
  313. }
  314. f << "],\nmin_cycles: [";
  315. first = true;
  316. for (const Aggregator &a : inAggregators)
  317. {
  318. if (!first)
  319. f << ",";
  320. first = false;
  321. f << a.mMinCyclesInCallWithChildren;
  322. }
  323. f << "],\nmax_cycles: [";
  324. first = true;
  325. for (const Aggregator &a : inAggregators)
  326. {
  327. if (!first)
  328. f << ",";
  329. first = false;
  330. f << a.mMaxCyclesInCallWithChildren;
  331. }
  332. f << "],\ncycles_per_frame: [";
  333. first = true;
  334. for (const Aggregator &a : inAggregators)
  335. {
  336. if (!first)
  337. f << ",";
  338. first = false;
  339. f << a.mTotalCyclesInCallWithChildren;
  340. }
  341. // Write footer
  342. f << R"(]};
  343. </script>
  344. <canvas id="canvas"></canvas>
  345. <div id="tooltip"></div>
  346. </tbody></table></body></html>)";
  347. }
  348. JPH_NAMESPACE_END
  349. #endif // JPH_PROFILE_ENABLED