profiler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #if defined(TORQUE_OS_WIN)
  24. #include<Windows.h> // for SetThreadAffinityMask
  25. #endif
  26. #if defined(TORQUE_OS_MAC)
  27. #include <CoreServices/CoreServices.h> // For high resolution timer
  28. #endif
  29. #include "core/stream/fileStream.h"
  30. #include "core/frameAllocator.h"
  31. #include "core/strings/stringFunctions.h"
  32. #include "core/stringTable.h"
  33. #include "platform/profiler.h"
  34. #include "platform/threads/thread.h"
  35. #include "console/engineAPI.h"
  36. #ifdef TORQUE_ENABLE_PROFILER
  37. ProfilerRootData *ProfilerRootData::sRootList = NULL;
  38. Profiler *gProfiler = NULL;
  39. // Uncomment the following line to enable a debugging aid for mismatched profiler blocks.
  40. //#define TORQUE_PROFILER_DEBUG
  41. // Machinery to record the stack of node names, as a debugging aid to find
  42. // mismatched PROFILE_START and PROFILE_END blocks. We profile from the
  43. // beginning to catch profile block errors that occur when torque is starting up.
  44. #ifdef TORQUE_PROFILER_DEBUG
  45. Vector<StringTableEntry> gProfilerNodeStack;
  46. #define TORQUE_PROFILE_AT_ENGINE_START true
  47. #define PROFILER_DEBUG_PUSH_NODE( nodename ) \
  48. gProfilerNodeStack.push_back( nodename );
  49. #define PROFILER_DEBUG_POP_NODE() \
  50. gProfilerNodeStack.pop_back();
  51. #else
  52. #define TORQUE_PROFILE_AT_ENGINE_START false
  53. #define PROFILER_DEBUG_PUSH_NODE( nodename ) ;
  54. #define PROFILER_DEBUG_POP_NODE() ;
  55. #endif
  56. #if defined(TORQUE_SUPPORTS_VC_INLINE_X86_ASM)
  57. // platform specific get hires times...
  58. void startHighResolutionTimer(U32 time[2])
  59. {
  60. //time[0] = Platform::getRealMilliseconds();
  61. __asm
  62. {
  63. push eax
  64. push edx
  65. push ecx
  66. rdtsc
  67. mov ecx, time
  68. mov DWORD PTR [ecx], eax
  69. mov DWORD PTR [ecx + 4], edx
  70. pop ecx
  71. pop edx
  72. pop eax
  73. }
  74. }
  75. U32 endHighResolutionTimer(U32 time[2])
  76. {
  77. U32 ticks;
  78. //ticks = Platform::getRealMilliseconds() - time[0];
  79. //return ticks;
  80. __asm
  81. {
  82. push eax
  83. push edx
  84. push ecx
  85. //db 0fh, 31h
  86. rdtsc
  87. mov ecx, time
  88. sub edx, DWORD PTR [ecx+4]
  89. sbb eax, DWORD PTR [ecx]
  90. mov DWORD PTR ticks, eax
  91. pop ecx
  92. pop edx
  93. pop eax
  94. }
  95. return ticks;
  96. }
  97. #elif defined(TORQUE_SUPPORTS_GCC_INLINE_X86_ASM)
  98. // platform specific get hires times...
  99. void startHighResolutionTimer(U32 time[2])
  100. {
  101. __asm__ __volatile__(
  102. "rdtsc\n"
  103. : "=a" (time[0]), "=d" (time[1])
  104. );
  105. }
  106. U32 endHighResolutionTimer(U32 time[2])
  107. {
  108. U32 ticks;
  109. __asm__ __volatile__(
  110. "rdtsc\n"
  111. "sub 0x4(%%ecx), %%edx\n"
  112. "sbb (%%ecx), %%eax\n"
  113. : "=a" (ticks) : "c" (time)
  114. );
  115. return ticks;
  116. }
  117. #elif defined(TORQUE_OS_MAC)
  118. void startHighResolutionTimer(U32 time[2]) {
  119. UnsignedWide t;
  120. Microseconds(&t);
  121. time[0] = t.lo;
  122. time[1] = t.hi;
  123. }
  124. U32 endHighResolutionTimer(U32 time[2]) {
  125. UnsignedWide t;
  126. Microseconds(&t);
  127. return t.lo - time[0];
  128. // given that we're returning a 32 bit integer, and this is unsigned subtraction...
  129. // it will just wrap around, we don't need the upper word of the time.
  130. // NOTE: the code assumes that more than 3 hrs will not go by between calls to startHighResolutionTimer() and endHighResolutionTimer().
  131. // I mean... that damn well better not happen anyway.
  132. }
  133. #else
  134. void startHighResolutionTimer(U32 time[2])
  135. {
  136. time[0] = Platform::getRealMilliseconds();
  137. }
  138. U32 endHighResolutionTimer(U32 time[2])
  139. {
  140. U32 ticks = Platform::getRealMilliseconds() - time[0];
  141. return ticks;
  142. }
  143. #endif
  144. Profiler::Profiler()
  145. {
  146. mMaxStackDepth = MaxStackDepth;
  147. mCurrentHash = 0;
  148. mCurrentProfilerData = (ProfilerData *) malloc(sizeof(ProfilerData));
  149. mCurrentProfilerData->mRoot = NULL;
  150. mCurrentProfilerData->mNextForRoot = NULL;
  151. mCurrentProfilerData->mNextProfilerData = NULL;
  152. mCurrentProfilerData->mNextHash = NULL;
  153. mCurrentProfilerData->mParent = NULL;
  154. mCurrentProfilerData->mNextSibling = NULL;
  155. mCurrentProfilerData->mFirstChild = NULL;
  156. mCurrentProfilerData->mLastSeenProfiler = NULL;
  157. mCurrentProfilerData->mHash = 0;
  158. mCurrentProfilerData->mSubDepth = 0;
  159. mCurrentProfilerData->mInvokeCount = 0;
  160. mCurrentProfilerData->mTotalTime = 0;
  161. mCurrentProfilerData->mSubTime = 0;
  162. #ifdef TORQUE_ENABLE_PROFILE_PATH
  163. mCurrentProfilerData->mPath = "";
  164. #endif
  165. mRootProfilerData = mCurrentProfilerData;
  166. for(U32 i = 0; i < ProfilerData::HashTableSize; i++)
  167. mCurrentProfilerData->mChildHash[i] = 0;
  168. mProfileList = NULL;
  169. mEnabled = TORQUE_PROFILE_AT_ENGINE_START;
  170. mNextEnable = TORQUE_PROFILE_AT_ENGINE_START;
  171. mStackDepth = 0;
  172. gProfiler = this;
  173. mDumpToConsole = false;
  174. mDumpToFile = false;
  175. mDumpFileName[0] = '\0';
  176. }
  177. Profiler::~Profiler()
  178. {
  179. reset();
  180. free(mRootProfilerData);
  181. gProfiler = NULL;
  182. }
  183. void Profiler::reset()
  184. {
  185. mEnabled = false; // in case we're in a profiler call.
  186. ProfilerData * head = mProfileList;
  187. ProfilerData * curr = NULL;
  188. while ((curr = head) != NULL)
  189. {
  190. head = head->mNextProfilerData;
  191. free(curr);
  192. }
  193. for(ProfilerRootData *walk = ProfilerRootData::sRootList; walk; walk = walk->mNextRoot)
  194. {
  195. walk->mFirstProfilerData = 0;
  196. walk->mTotalTime = 0;
  197. walk->mSubTime = 0;
  198. walk->mTotalInvokeCount = 0;
  199. }
  200. mCurrentProfilerData = mRootProfilerData;
  201. mCurrentProfilerData->mNextForRoot = 0;
  202. mCurrentProfilerData->mFirstChild = 0;
  203. for(U32 i = 0; i < ProfilerData::HashTableSize; i++)
  204. mCurrentProfilerData->mChildHash[i] = 0;
  205. mCurrentProfilerData->mInvokeCount = 0;
  206. mCurrentProfilerData->mTotalTime = 0;
  207. mCurrentProfilerData->mSubTime = 0;
  208. mCurrentProfilerData->mSubDepth = 0;
  209. mCurrentProfilerData->mLastSeenProfiler = 0;
  210. }
  211. static Profiler aProfiler; // allocate the global profiler
  212. ProfilerRootData::ProfilerRootData(const char *name)
  213. {
  214. for(ProfilerRootData *walk = sRootList; walk; walk = walk->mNextRoot)
  215. if(!dStrcmp(walk->mName, name))
  216. AssertFatal( false, avar( "Duplicate profile name: %s", name ) );
  217. mName = name;
  218. mNameHash = _StringTable::hashString(name);
  219. mNextRoot = sRootList;
  220. sRootList = this;
  221. mTotalTime = 0;
  222. mTotalInvokeCount = 0;
  223. mFirstProfilerData = NULL;
  224. mEnabled = true;
  225. }
  226. void Profiler::validate()
  227. {
  228. for(ProfilerRootData *walk = ProfilerRootData::sRootList; walk; walk = walk->mNextRoot)
  229. {
  230. for(ProfilerData *dp = walk->mFirstProfilerData; dp; dp = dp->mNextForRoot)
  231. {
  232. if(dp->mRoot != walk)
  233. Platform::debugBreak();
  234. // check if it's in the parent's list...
  235. ProfilerData *wk;
  236. for(wk = dp->mParent->mFirstChild; wk; wk = wk->mNextSibling)
  237. if(wk == dp)
  238. break;
  239. if(!wk)
  240. Platform::debugBreak();
  241. for(wk = dp->mParent->mChildHash[walk->mNameHash & (ProfilerData::HashTableSize - 1)] ;
  242. wk; wk = wk->mNextHash)
  243. if(wk == dp)
  244. break;
  245. if(!wk)
  246. Platform::debugBreak();
  247. }
  248. }
  249. }
  250. #ifdef TORQUE_ENABLE_PROFILE_PATH
  251. const char * Profiler::getProfilePath()
  252. {
  253. #ifdef TORQUE_MULTITHREAD
  254. // Ignore non-main-thread profiler activity.
  255. if( !ThreadManager::isMainThread() )
  256. return "[non-main thread]";
  257. #endif
  258. return (mEnabled && mCurrentProfilerData) ? mCurrentProfilerData->mPath : "na";
  259. }
  260. #endif
  261. #ifdef TORQUE_ENABLE_PROFILE_PATH
  262. const char * Profiler::constructProfilePath(ProfilerData * pd)
  263. {
  264. if (pd->mParent)
  265. {
  266. const bool saveEnable = gProfiler->mEnabled;
  267. gProfiler->mEnabled = false;
  268. const char * connector = " -> ";
  269. U32 len = dStrlen(pd->mParent->mPath);
  270. if (!len)
  271. connector = "";
  272. len += dStrlen(connector);
  273. len += dStrlen(pd->mRoot->mName);
  274. U32 mark = FrameAllocator::getWaterMark();
  275. char * buf = (char*)FrameAllocator::alloc(len+1);
  276. dStrcpy(buf,pd->mParent->mPath);
  277. dStrcat(buf,connector);
  278. dStrcat(buf,pd->mRoot->mName);
  279. const char * ret = StringTable->insert(buf);
  280. FrameAllocator::setWaterMark(mark);
  281. gProfiler->mEnabled = saveEnable;
  282. return ret;
  283. }
  284. return "root";
  285. }
  286. #endif
  287. void Profiler::hashPush(ProfilerRootData *root)
  288. {
  289. #ifdef TORQUE_MULTITHREAD
  290. // Ignore non-main-thread profiler activity.
  291. if( !ThreadManager::isMainThread() )
  292. return;
  293. #endif
  294. mStackDepth++;
  295. PROFILER_DEBUG_PUSH_NODE(root->mName);
  296. AssertFatal(mStackDepth <= mMaxStackDepth,
  297. "Stack overflow in profiler. You may have mismatched PROFILE_START and PROFILE_ENDs");
  298. if(!mEnabled)
  299. return;
  300. ProfilerData *nextProfiler = NULL;
  301. if(!root->mEnabled || mCurrentProfilerData->mRoot == root)
  302. {
  303. mCurrentProfilerData->mSubDepth++;
  304. return;
  305. }
  306. if(mCurrentProfilerData->mLastSeenProfiler &&
  307. mCurrentProfilerData->mLastSeenProfiler->mRoot == root)
  308. nextProfiler = mCurrentProfilerData->mLastSeenProfiler;
  309. if(!nextProfiler)
  310. {
  311. // first see if it's in the hash table...
  312. U32 index = root->mNameHash & (ProfilerData::HashTableSize - 1);
  313. nextProfiler = mCurrentProfilerData->mChildHash[index];
  314. while(nextProfiler)
  315. {
  316. if(nextProfiler->mRoot == root)
  317. break;
  318. nextProfiler = nextProfiler->mNextHash;
  319. }
  320. if(!nextProfiler)
  321. {
  322. nextProfiler = (ProfilerData *) malloc(sizeof(ProfilerData));
  323. for(U32 i = 0; i < ProfilerData::HashTableSize; i++)
  324. nextProfiler->mChildHash[i] = 0;
  325. nextProfiler->mRoot = root;
  326. nextProfiler->mNextForRoot = root->mFirstProfilerData;
  327. root->mFirstProfilerData = nextProfiler;
  328. nextProfiler->mNextProfilerData = mProfileList;
  329. mProfileList = nextProfiler;
  330. nextProfiler->mNextHash = mCurrentProfilerData->mChildHash[index];
  331. mCurrentProfilerData->mChildHash[index] = nextProfiler;
  332. nextProfiler->mParent = mCurrentProfilerData;
  333. nextProfiler->mNextSibling = mCurrentProfilerData->mFirstChild;
  334. mCurrentProfilerData->mFirstChild = nextProfiler;
  335. nextProfiler->mFirstChild = NULL;
  336. nextProfiler->mLastSeenProfiler = NULL;
  337. nextProfiler->mHash = root->mNameHash;
  338. nextProfiler->mInvokeCount = 0;
  339. nextProfiler->mTotalTime = 0;
  340. nextProfiler->mSubTime = 0;
  341. nextProfiler->mSubDepth = 0;
  342. #ifdef TORQUE_ENABLE_PROFILE_PATH
  343. nextProfiler->mPath = constructProfilePath(nextProfiler);
  344. #endif
  345. }
  346. }
  347. root->mTotalInvokeCount++;
  348. nextProfiler->mInvokeCount++;
  349. startHighResolutionTimer(nextProfiler->mStartTime);
  350. mCurrentProfilerData->mLastSeenProfiler = nextProfiler;
  351. mCurrentProfilerData = nextProfiler;
  352. }
  353. void Profiler::enable(bool enabled)
  354. {
  355. mNextEnable = enabled;
  356. }
  357. void Profiler::dumpToConsole()
  358. {
  359. mDumpToConsole = true;
  360. mDumpToFile = false;
  361. mDumpFileName[0] = '\0';
  362. }
  363. void Profiler::dumpToFile(const char* fileName)
  364. {
  365. AssertFatal(dStrlen(fileName) < DumpFileNameLength, "Error, dump filename too long");
  366. mDumpToFile = true;
  367. mDumpToConsole = false;
  368. dStrcpy(mDumpFileName, fileName);
  369. }
  370. void Profiler::hashPop(ProfilerRootData *expected)
  371. {
  372. #ifdef TORQUE_MULTITHREAD
  373. // Ignore non-main-thread profiler activity.
  374. if( !ThreadManager::isMainThread() )
  375. return;
  376. #endif
  377. mStackDepth--;
  378. PROFILER_DEBUG_POP_NODE();
  379. AssertFatal(mStackDepth >= 0, "Stack underflow in profiler. You may have mismatched PROFILE_START and PROFILE_ENDs");
  380. if(mEnabled)
  381. {
  382. if(mCurrentProfilerData->mSubDepth)
  383. {
  384. mCurrentProfilerData->mSubDepth--;
  385. return;
  386. }
  387. if(expected)
  388. {
  389. AssertISV(expected == mCurrentProfilerData->mRoot, "Profiler::hashPop - didn't get expected ProfilerRoot!");
  390. }
  391. F64 fElapsed = endHighResolutionTimer(mCurrentProfilerData->mStartTime);
  392. mCurrentProfilerData->mTotalTime += fElapsed;
  393. mCurrentProfilerData->mParent->mSubTime += fElapsed; // mark it in the parent as well...
  394. mCurrentProfilerData->mRoot->mTotalTime += fElapsed;
  395. if(mCurrentProfilerData->mParent->mRoot)
  396. mCurrentProfilerData->mParent->mRoot->mSubTime += fElapsed; // mark it in the parent as well...
  397. mCurrentProfilerData = mCurrentProfilerData->mParent;
  398. }
  399. if(mStackDepth == 0)
  400. {
  401. // apply the next enable...
  402. if(mDumpToConsole || mDumpToFile)
  403. {
  404. dump();
  405. startHighResolutionTimer(mCurrentProfilerData->mStartTime);
  406. }
  407. if(!mEnabled && mNextEnable)
  408. startHighResolutionTimer(mCurrentProfilerData->mStartTime);
  409. #if defined(TORQUE_OS_WIN)
  410. // The high performance counters under win32 are unreliable when running on multiple
  411. // processors. When the profiler is enabled, we restrict Torque to a single processor.
  412. if(mNextEnable != mEnabled)
  413. {
  414. if(mNextEnable)
  415. {
  416. Con::warnf("Warning: forcing the Torque profiler thread to run only on cpu 1.");
  417. SetThreadAffinityMask(GetCurrentThread(), 1);
  418. }
  419. else
  420. {
  421. Con::warnf("Warning: the Torque profiler thread may now run on any cpu.");
  422. DWORD_PTR procMask;
  423. DWORD_PTR sysMask;
  424. GetProcessAffinityMask( GetCurrentProcess(), &procMask, &sysMask);
  425. SetThreadAffinityMask( GetCurrentThread(), procMask);
  426. }
  427. }
  428. #endif
  429. mEnabled = mNextEnable;
  430. }
  431. }
  432. static S32 QSORT_CALLBACK rootDataCompare(const void *s1, const void *s2)
  433. {
  434. const ProfilerRootData *r1 = *((ProfilerRootData **) s1);
  435. const ProfilerRootData *r2 = *((ProfilerRootData **) s2);
  436. if((r2->mTotalTime - r2->mSubTime) > (r1->mTotalTime - r1->mSubTime))
  437. return 1;
  438. return -1;
  439. }
  440. static void profilerDataDumpRecurse(ProfilerData *data, char *buffer, U32 bufferLen, F64 totalTime)
  441. {
  442. // dump out this one:
  443. Con::printf("%7.3f %7.3f %8d %s%s",
  444. 100 * data->mTotalTime / totalTime,
  445. 100 * (data->mTotalTime - data->mSubTime) / totalTime,
  446. data->mInvokeCount,
  447. buffer,
  448. data->mRoot ? data->mRoot->mName : "ROOT" );
  449. data->mTotalTime = 0;
  450. data->mSubTime = 0;
  451. data->mInvokeCount = 0;
  452. buffer[bufferLen] = ' ';
  453. buffer[bufferLen+1] = ' ';
  454. buffer[bufferLen+2] = 0;
  455. // sort data's children...
  456. ProfilerData *list = NULL;
  457. while(data->mFirstChild)
  458. {
  459. ProfilerData *ins = data->mFirstChild;
  460. data->mFirstChild = ins->mNextSibling;
  461. ProfilerData **walk = &list;
  462. while(*walk && (*walk)->mTotalTime > ins->mTotalTime)
  463. walk = &(*walk)->mNextSibling;
  464. ins->mNextSibling = *walk;
  465. *walk = ins;
  466. }
  467. data->mFirstChild = list;
  468. while(list)
  469. {
  470. if(list->mInvokeCount)
  471. profilerDataDumpRecurse(list, buffer, bufferLen + 2, totalTime);
  472. list = list->mNextSibling;
  473. }
  474. buffer[bufferLen] = 0;
  475. }
  476. static void profilerDataDumpRecurseFile(ProfilerData *data, char *buffer, U32 bufferLen, F64 totalTime, FileStream& fws)
  477. {
  478. char pbuffer[256];
  479. dSprintf(pbuffer, 255, "%7.3f %7.3f %8d %s%s\n",
  480. 100 * data->mTotalTime / totalTime,
  481. 100 * (data->mTotalTime - data->mSubTime) / totalTime,
  482. data->mInvokeCount,
  483. buffer,
  484. data->mRoot ? data->mRoot->mName : "ROOT" );
  485. fws.write(dStrlen(pbuffer), pbuffer);
  486. data->mTotalTime = 0;
  487. data->mSubTime = 0;
  488. data->mInvokeCount = 0;
  489. buffer[bufferLen] = ' ';
  490. buffer[bufferLen+1] = ' ';
  491. buffer[bufferLen+2] = 0;
  492. // sort data's children...
  493. ProfilerData *list = NULL;
  494. while(data->mFirstChild)
  495. {
  496. ProfilerData *ins = data->mFirstChild;
  497. data->mFirstChild = ins->mNextSibling;
  498. ProfilerData **walk = &list;
  499. while(*walk && (*walk)->mTotalTime > ins->mTotalTime)
  500. walk = &(*walk)->mNextSibling;
  501. ins->mNextSibling = *walk;
  502. *walk = ins;
  503. }
  504. data->mFirstChild = list;
  505. while(list)
  506. {
  507. if(list->mInvokeCount)
  508. profilerDataDumpRecurseFile(list, buffer, bufferLen + 2, totalTime, fws);
  509. list = list->mNextSibling;
  510. }
  511. buffer[bufferLen] = 0;
  512. }
  513. void Profiler::dump()
  514. {
  515. bool enableSave = mEnabled;
  516. mEnabled = false;
  517. mStackDepth++;
  518. // may have some profiled calls... gotta turn em off.
  519. Vector<ProfilerRootData *> rootVector;
  520. F64 totalTime = 0;
  521. for(ProfilerRootData *walk = ProfilerRootData::sRootList; walk; walk = walk->mNextRoot)
  522. {
  523. totalTime += walk->mTotalTime - walk->mSubTime;
  524. rootVector.push_back(walk);
  525. }
  526. dQsort((void *) &rootVector[0], rootVector.size(), sizeof(ProfilerRootData *), rootDataCompare);
  527. if (mDumpToConsole == true)
  528. {
  529. Con::printf("Profiler Data Dump:");
  530. Con::printf("Ordered by non-sub total time -");
  531. Con::printf("%%NSTime %% Time Invoke # Name");
  532. for(U32 i = 0; i < rootVector.size(); i++)
  533. {
  534. Con::printf("%7.3f %7.3f %8d %s",
  535. 100 * (rootVector[i]->mTotalTime - rootVector[i]->mSubTime) / totalTime,
  536. 100 * rootVector[i]->mTotalTime / totalTime,
  537. rootVector[i]->mTotalInvokeCount,
  538. rootVector[i]->mName);
  539. rootVector[i]->mTotalInvokeCount = 0;
  540. rootVector[i]->mTotalTime = 0;
  541. rootVector[i]->mSubTime = 0;
  542. }
  543. Con::printf("");
  544. Con::printf("Ordered by stack trace total time -");
  545. Con::printf("%% Time %% NSTime Invoke # Name");
  546. mCurrentProfilerData->mTotalTime = endHighResolutionTimer(mCurrentProfilerData->mStartTime);
  547. char depthBuffer[MaxStackDepth * 2 + 1];
  548. depthBuffer[0] = 0;
  549. profilerDataDumpRecurse(mCurrentProfilerData, depthBuffer, 0, totalTime);
  550. mEnabled = enableSave;
  551. mStackDepth--;
  552. }
  553. else if (mDumpToFile == true && mDumpFileName[0] != '\0')
  554. {
  555. FileStream fws;
  556. bool success = fws.open(mDumpFileName, Torque::FS::File::Write);
  557. AssertFatal(success, "Cannot write profile dump to specified file!");
  558. char buffer[1024];
  559. dStrcpy(buffer, "Profiler Data Dump:\n");
  560. fws.write(dStrlen(buffer), buffer);
  561. dStrcpy(buffer, "Ordered by non-sub total time -\n");
  562. fws.write(dStrlen(buffer), buffer);
  563. dStrcpy(buffer, "%%NSTime %% Time Invoke # Name\n");
  564. fws.write(dStrlen(buffer), buffer);
  565. for(U32 i = 0; i < rootVector.size(); i++)
  566. {
  567. dSprintf(buffer, 1023, "%7.3f %7.3f %8d %s\n",
  568. 100 * (rootVector[i]->mTotalTime - rootVector[i]->mSubTime) / totalTime,
  569. 100 * rootVector[i]->mTotalTime / totalTime,
  570. rootVector[i]->mTotalInvokeCount,
  571. rootVector[i]->mName);
  572. fws.write(dStrlen(buffer), buffer);
  573. rootVector[i]->mTotalInvokeCount = 0;
  574. rootVector[i]->mTotalTime = 0;
  575. rootVector[i]->mSubTime = 0;
  576. }
  577. dStrcpy(buffer, "\nOrdered by non-sub total time -\n");
  578. fws.write(dStrlen(buffer), buffer);
  579. dStrcpy(buffer, "%%NSTime %% Time Invoke # Name\n");
  580. fws.write(dStrlen(buffer), buffer);
  581. mCurrentProfilerData->mTotalTime = endHighResolutionTimer(mCurrentProfilerData->mStartTime);
  582. char depthBuffer[MaxStackDepth * 2 + 1];
  583. depthBuffer[0] = 0;
  584. profilerDataDumpRecurseFile(mCurrentProfilerData, depthBuffer, 0, totalTime, fws);
  585. mEnabled = enableSave;
  586. mStackDepth--;
  587. fws.close();
  588. }
  589. mDumpToConsole = false;
  590. mDumpToFile = false;
  591. mDumpFileName[0] = '\0';
  592. }
  593. void Profiler::enableMarker(const char *marker, bool enable)
  594. {
  595. reset();
  596. U32 markerLen = dStrlen(marker);
  597. if(markerLen == 0)
  598. return;
  599. bool sn = marker[markerLen - 1] == '*';
  600. for(ProfilerRootData *data = ProfilerRootData::sRootList; data; data = data->mNextRoot)
  601. {
  602. if(sn)
  603. {
  604. if(!dStrncmp(marker, data->mName, markerLen - 1))
  605. data->mEnabled = enable;
  606. }
  607. else
  608. {
  609. if(!dStrcmp(marker, data->mName))
  610. data->mEnabled = enable;
  611. }
  612. }
  613. }
  614. //=============================================================================
  615. // Console Functions.
  616. //=============================================================================
  617. // MARK: ---- Console Functions ----
  618. //-----------------------------------------------------------------------------
  619. DefineEngineFunction( profilerMarkerEnable, void, ( const char* markerName, bool enable ), ( true ),
  620. "@brief Enable or disable a specific profile.\n\n"
  621. "@param enable Optional paramater to enable or disable the profile.\n"
  622. "@param markerName Name of a specific marker to enable or disable.\n"
  623. "@note Calling this function will first call profilerReset(), clearing all data from profiler. "
  624. "All profile markers are enabled by default.\n\n"
  625. "@ingroup Debugging")
  626. {
  627. if( gProfiler )
  628. gProfiler->enableMarker( markerName, enable );
  629. }
  630. //-----------------------------------------------------------------------------
  631. DefineEngineFunction( profilerEnable, void, ( bool enable ),,
  632. "@brief Enables or disables the profiler.\n\n"
  633. "Data is only gathered while the profiler is enabled.\n\n"
  634. "@note Profiler is not available in shipping builds.\n"
  635. "T3D has predefined profiling areas surrounded by markers, "
  636. "but you may need to define additional markers (in C++) around areas you wish to profile,"
  637. " by using the PROFILE_START( markerName ); and PROFILE_END(); macros.\n\n"
  638. "@ingroup Debugging\n" )
  639. {
  640. if(gProfiler)
  641. gProfiler->enable(enable);
  642. }
  643. DefineEngineFunction(profilerDump, void, (),,
  644. "@brief Dumps current profiling stats to the console window.\n\n"
  645. "@note Markers disabled with profilerMarkerEnable() will be skipped over. "
  646. "If the profiler is currently running, it will be disabled.\n"
  647. "@ingroup Debugging")
  648. {
  649. if(gProfiler)
  650. gProfiler->dumpToConsole();
  651. }
  652. DefineEngineFunction( profilerDumpToFile, void, ( const char* fileName ),,
  653. "@brief Dumps current profiling stats to a file.\n\n"
  654. "@note If the profiler is currently running, it will be disabled.\n"
  655. "@param fileName Name and path of file to save profiling stats to. Must use forward slashes (/). "
  656. "Will attempt to create the file if it does not already exist.\n"
  657. "@tsexample\n"
  658. "profilerDumpToFile( \"C:/Torque/log1.txt\" );\n"
  659. "@endtsexample\n\n"
  660. "@ingroup Debugging" )
  661. {
  662. if(gProfiler)
  663. gProfiler->dumpToFile(fileName);
  664. }
  665. DefineEngineFunction( profilerReset, void, (),,
  666. "@brief Resets the profiler, clearing it of all its data.\n\n"
  667. "If the profiler is currently running, it will first be disabled. "
  668. "All markers will retain their current enabled/disabled status.\n\n"
  669. "@ingroup Debugging" )
  670. {
  671. if(gProfiler)
  672. gProfiler->reset();
  673. }
  674. #endif