Profiler.cpp 9.0 KB

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