Profiler.cpp 11 KB

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