BsProfilerCPU.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. //__________________________ Banshee Project - A modern game development toolkit _________________________________//
  2. //_____________________________________ www.banshee-project.com __________________________________________________//
  3. //________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
  4. #pragma once
  5. #include "BsCorePrerequisites.h"
  6. #include "BsModule.h"
  7. namespace BansheeEngine
  8. {
  9. class CPUProfilerReport;
  10. /**
  11. * @brief Provides various performance measuring methods.
  12. *
  13. * @note Thread safe. Matching begin*\end* calls
  14. * must belong to the same thread though.
  15. */
  16. class BS_CORE_EXPORT ProfilerCPU : public Module<ProfilerCPU>
  17. {
  18. /**
  19. * @brief Timer class responsible for tracking elapsed time.
  20. */
  21. class Timer
  22. {
  23. public:
  24. Timer();
  25. /**
  26. * @brief Sets the start time for the timer.
  27. */
  28. void start();
  29. /**
  30. * @brief Stops the timer and calculates the elapsed time
  31. * from start time to now.
  32. */
  33. void stop();
  34. /**
  35. * @brief Resets the elapsed time to zero.
  36. */
  37. void reset();
  38. double time;
  39. private:
  40. double startTime;
  41. /**
  42. * @brief Returns time elapsed since CPU was started in millseconds.
  43. */
  44. static inline double getCurrentTime();
  45. };
  46. /**
  47. * @brief Timer class responsible for tracking number of elapsed CPU cycles.
  48. */
  49. class TimerPrecise
  50. {
  51. public:
  52. TimerPrecise();
  53. /**
  54. * @brief Starts the counter marking the current number of executed
  55. * CPU cycles since CPU was started.
  56. */
  57. void start();
  58. /**
  59. * @brief Ends the counter and calculates the number of CPU cycles between
  60. * now and the start time.
  61. */
  62. void stop();
  63. /**
  64. * @brief Resets the cycle count to zero.
  65. */
  66. void reset();
  67. UINT64 cycles;
  68. private:
  69. UINT64 startCycles;
  70. /**
  71. * @brief Queries the CPU for the current number of CPU cycles executed since the
  72. * program was started.
  73. */
  74. static inline UINT64 getNumCycles();
  75. };
  76. /**
  77. * @brief Contains data about a single profiler sample (counting time in milliseconds).
  78. *
  79. * @note A sample is created whenever a named profile block is entered. e.g. if you have a function
  80. * you are profiling, and it gets called 10 times, there will be 10 samples.
  81. */
  82. struct ProfileSample
  83. {
  84. ProfileSample(double _time, UINT64 _numAllocs, UINT64 _numFrees)
  85. :time(_time), numAllocs(_numAllocs), numFrees(_numFrees)
  86. { }
  87. double time;
  88. UINT64 numAllocs;
  89. UINT64 numFrees;
  90. };
  91. /**
  92. * @brief Contains data about a single precise profiler sample (counting CPU cycles).
  93. *
  94. * @note A sample is created whenever a named profile block is entered. e.g. if you have a function
  95. * you are profiling, and it gets called 10 times, there will be 10 samples.
  96. */
  97. struct PreciseProfileSample
  98. {
  99. PreciseProfileSample(UINT64 _cycles, UINT64 _numAllocs, UINT64 _numFrees)
  100. :cycles(_cycles), numAllocs(_numAllocs), numFrees(_numFrees)
  101. { }
  102. UINT64 cycles;
  103. UINT64 numAllocs;
  104. UINT64 numFrees;
  105. };
  106. /**
  107. * @brief Contains basic (time based) profiling data contained in a profiling block.
  108. */
  109. struct ProfileData
  110. {
  111. /**
  112. * @brief Begins a new sample and records current sample state. Previous sample must
  113. * not be active.
  114. */
  115. void beginSample();
  116. /**
  117. * @brief Records current sample state and creates a new sample based on start and end state.
  118. * Adds the sample to the sample list.
  119. */
  120. void endSample();
  121. /**
  122. * @brief Removes the last added sample from the sample list and makes it active again. You must
  123. * call endSample when done as if you called beginSample.
  124. */
  125. void resumeLastSample();
  126. ProfilerVector<ProfileSample> samples;
  127. Timer timer;
  128. UINT64 memAllocs;
  129. UINT64 memFrees;
  130. };
  131. /**
  132. * @brief Contains precise (CPU cycle based) profiling data contained in a profiling block.
  133. */
  134. struct PreciseProfileData
  135. {
  136. /**
  137. * @brief Begins a new sample and records current sample state. Previous sample must
  138. * not be active.
  139. */
  140. void beginSample();
  141. /**
  142. * @brief Records current sample state and creates a new sample based on start and end state.
  143. * Adds the sample to the sample list.
  144. */
  145. void endSample();
  146. /**
  147. * @brief Removes the last added sample from the sample list and makes it active again. You must
  148. * call endSample when done as if you called beginSample.
  149. */
  150. void resumeLastSample();
  151. ProfilerVector<PreciseProfileSample> samples;
  152. TimerPrecise timer;
  153. UINT64 memAllocs;
  154. UINT64 memFrees;
  155. };
  156. /**
  157. * @brief Contains all sampling information about a single named profiling block.
  158. * Each block has its own sampling information and optionally child blocks.
  159. */
  160. struct ProfiledBlock
  161. {
  162. ProfiledBlock();
  163. ~ProfiledBlock();
  164. /**
  165. * @brief Attempts to find a child block with the specified name. Returns
  166. * null if not found.
  167. */
  168. ProfiledBlock* findChild(const ProfilerString& name) const;
  169. ProfilerString name;
  170. ProfileData basic;
  171. PreciseProfileData precise;
  172. ProfilerVector<ProfiledBlock*> children;
  173. };
  174. /**
  175. * @brief CPU sampling type.
  176. */
  177. enum class ActiveSamplingType
  178. {
  179. Basic, /**< Sample using milliseconds. */
  180. Precise /**< Sample using CPU cycles. */
  181. };
  182. /**
  183. * @brief Contains data about the currently active profiling block.
  184. */
  185. struct ActiveBlock
  186. {
  187. ActiveBlock()
  188. :type(ActiveSamplingType::Basic), block(nullptr)
  189. { }
  190. ActiveBlock(ActiveSamplingType _type, ProfiledBlock* _block)
  191. :type(_type), block(_block)
  192. { }
  193. ActiveSamplingType type;
  194. ProfiledBlock* block;
  195. };
  196. /**
  197. * @brief Contains data about an active profiling thread.
  198. */
  199. struct ThreadInfo
  200. {
  201. ThreadInfo();
  202. /**
  203. * @brief Starts profiling on the thread. New primary profiling block
  204. * is created with the given name.
  205. */
  206. void begin(const ProfilerString& _name);
  207. /**
  208. * @brief Ends profiling on the thread. You should end all samples before calling this,
  209. * but if you don't they will be terminated automatically.
  210. */
  211. void end();
  212. /**
  213. * @brief Deletes all internal profiling data and makes the object ready for another
  214. * iteration. Should be called after end in order to delete any existing data.
  215. */
  216. void reset();
  217. /**
  218. * @brief Gets the primary profiling block used by the thread.
  219. */
  220. ProfiledBlock* getBlock();
  221. /**
  222. * @brief Deletes the provided block.
  223. */
  224. void releaseBlock(ProfiledBlock* block);
  225. static BS_THREADLOCAL ThreadInfo* activeThread;
  226. bool isActive;
  227. ProfiledBlock* rootBlock;
  228. ProfilerStack<ActiveBlock> activeBlocks;
  229. ActiveBlock activeBlock;
  230. };
  231. public:
  232. ProfilerCPU();
  233. ~ProfilerCPU();
  234. /**
  235. * @brief Registers a new thread we will be doing sampling in. This needs to be called before any beginSample*\endSample* calls
  236. * are made in that thread.
  237. *
  238. * @param name Name that will allow you to more easily identify the thread.
  239. */
  240. void beginThread(const ProfilerString& name);
  241. /**
  242. * @brief Ends sampling for the current thread. No beginSample*\endSample* calls after this point.
  243. */
  244. void endThread();
  245. /**
  246. * @brief Begins sample measurement. Must be followed by endSample.
  247. *
  248. * @param name Unique name for the sample you can later use to find the sampling data.
  249. */
  250. void beginSample(const ProfilerString& name);
  251. /**
  252. * @brief Ends sample measurement.
  253. *
  254. * @param name Unique name for the sample.
  255. *
  256. * @note Unique name is primarily needed to more easily identify mismatched
  257. * begin/end sample pairs. Otherwise the name in beginSample would be enough.
  258. */
  259. void endSample(const ProfilerString& name);
  260. /**
  261. * @brief Begins sample measurement. Must be followed by endSample.
  262. *
  263. * @param name Unique name for the sample you can later use to find the sampling data.
  264. *
  265. * @note This method uses very precise CPU counters to determine variety of data not
  266. * provided by standard beginSample. However due to the way these counters work you should
  267. * not use this method for larger parts of code. It does not consider context switches so if the OS
  268. * decides to switch context between measurements you will get invalid data.
  269. */
  270. void beginSamplePrecise(const ProfilerString& name);
  271. /**
  272. * @brief Ends precise sample measurement.
  273. *
  274. * @param name Unique name for the sample.
  275. *
  276. * @note Unique name is primarily needed to more easily identify mismatched
  277. * begin/end sample pairs. Otherwise the name in beginSamplePrecise would be enough.
  278. */
  279. void endSamplePrecise(const ProfilerString& name);
  280. /**
  281. * @brief Clears all sampling data, and ends any unfinished sampling blocks.
  282. */
  283. void reset();
  284. /**
  285. * @brief Generates a report from all previously sampled data.
  286. *
  287. * @note Generating a report will stop all in-progress sampling. You should make sure
  288. * you call endSample* manually beforehand so this doesn't have to happen.
  289. */
  290. CPUProfilerReport generateReport();
  291. private:
  292. /**
  293. * @brief Calculates overhead that the timing and sampling methods themselves introduce
  294. * so we might get more accurate measurements when creating reports.
  295. */
  296. void estimateTimerOverhead();
  297. private:
  298. double mBasicTimerOverhead;
  299. UINT64 mPreciseTimerOverhead;
  300. double mBasicSamplingOverheadMs;
  301. double mPreciseSamplingOverheadMs;
  302. UINT64 mBasicSamplingOverheadCycles;
  303. UINT64 mPreciseSamplingOverheadCycles;
  304. ProfilerVector<ThreadInfo*> mActiveThreads;
  305. BS_MUTEX(mThreadSync);
  306. };
  307. /**
  308. * @brief Profiling entry containing information about a single CPU profiling block
  309. * containing timing information.
  310. */
  311. struct BS_CORE_EXPORT CPUProfilerBasicSamplingEntry
  312. {
  313. struct BS_CORE_EXPORT Data
  314. {
  315. Data();
  316. String name; /**< Name of the profiling block. */
  317. UINT32 numCalls; /**< Number of times the block was entered. */
  318. UINT64 memAllocs; /**< Number of memory allocations that happened within the block. */
  319. UINT64 memFrees; /**< Number of memory deallocations that happened within the block. */
  320. double avgTimeMs; /**< Average time it took to execute the block, per call. In milliseconds. */
  321. double maxTimeMs; /**< Maximum time of a single call in the block. In milliseconds. */
  322. double totalTimeMs; /**< Total time the block took, across all calls. In milliseconds. */
  323. double avgSelfTimeMs; /**< Average time it took to execute the block, per call. Ignores time used by child blocks. In milliseconds. */
  324. double totalSelfTimeMs; /**< Total time the block took, across all calls. Ignores time used by child blocks. In milliseconds. */
  325. double estimatedSelfOverheadMs; /**< Estimated overhead of profiling methods, only for this exact block. In milliseconds. */
  326. double estimatedOverheadMs; /**< Estimated overhead of profiling methods for this block and all children. In milliseconds. */
  327. float pctOfParent; /**< Percent of parent block time this block took to execute. Ranging [0.0, 1.0]. */
  328. } data;
  329. ProfilerVector<CPUProfilerBasicSamplingEntry> childEntries;
  330. };
  331. /**
  332. * @brief Profiling entry containing information about a single CPU profiling block
  333. * containing CPU cycle count based information.
  334. */
  335. struct BS_CORE_EXPORT CPUProfilerPreciseSamplingEntry
  336. {
  337. struct BS_CORE_EXPORT Data
  338. {
  339. Data();
  340. String name; /**< Name of the profiling block. */
  341. UINT32 numCalls; /**< Number of times the block was entered. */
  342. UINT64 memAllocs; /**< Number of memory allocations that happened within the block. */
  343. UINT64 memFrees; /**< Number of memory deallocations that happened within the block. */
  344. UINT64 avgCycles; /**< Average number of cycles it took to execute the block, per call. */
  345. UINT64 maxCycles; /**< Maximum number of cycles of a single call in the block. */
  346. UINT64 totalCycles; /**< Total number of cycles across all calls in the block. */
  347. UINT64 avgSelfCycles; /**< Average number of cycles it took to execute the block, per call. Ignores cycles used by child blocks. */
  348. UINT64 totalSelfCycles; /**< Total number of cycles across all calls in the block. Ignores time used by child blocks. */
  349. UINT64 estimatedSelfOverhead; /**< Estimated overhead of profiling methods, only for this exact block. In cycles. */
  350. UINT64 estimatedOverhead; /**< Estimated overhead of profiling methods for this block and all children. In cycles. */
  351. float pctOfParent; /**< Percent of parent block cycles used by this block. Ranging [0.0, 1.0]. */
  352. } data;
  353. ProfilerVector<CPUProfilerPreciseSamplingEntry> childEntries;
  354. };
  355. /**
  356. * @brief CPU profiling report containing all profiling information for a single profiling session.
  357. */
  358. class BS_CORE_EXPORT CPUProfilerReport
  359. {
  360. public:
  361. CPUProfilerReport();
  362. /**
  363. * @brief Returns root entry for the basic (time based) sampling data. Root entry always contains the
  364. * profiling block associated with the entire thread.
  365. */
  366. const CPUProfilerBasicSamplingEntry& getBasicSamplingData() const { return mBasicSamplingRootEntry; }
  367. /**
  368. * @brief Returns root entry for the precise (CPU cycle based) sampling data. Root entry always contains the
  369. * profiling block associated with the entire thread.
  370. */
  371. const CPUProfilerPreciseSamplingEntry& getPreciseSamplingData() const { return mPreciseSamplingRootEntry; }
  372. private:
  373. friend class ProfilerCPU;
  374. CPUProfilerBasicSamplingEntry mBasicSamplingRootEntry;
  375. CPUProfilerPreciseSamplingEntry mPreciseSamplingRootEntry;
  376. };
  377. /**
  378. * @brief Quick way to access the CPU profiler.
  379. */
  380. BS_CORE_EXPORT ProfilerCPU& gProfilerCPU();
  381. /**
  382. * @brief Shortcut for profiling a single function call.
  383. */
  384. #define PROFILE_CALL(call, name) \
  385. BansheeEngine::gProfilerCPU().beginSample(##name##); \
  386. call; \
  387. BansheeEngine::gProfilerCPU().endSample(##name##);
  388. }