profiler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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 = head;
  188. while ( curr )
  189. {
  190. head = curr->mNextProfilerData;
  191. free( curr );
  192. if ( head )
  193. curr = head;
  194. else
  195. curr = NULL;
  196. }
  197. mProfileList = NULL;
  198. for(ProfilerRootData *walk = ProfilerRootData::sRootList; walk; walk = walk->mNextRoot)
  199. {
  200. walk->mFirstProfilerData = 0;
  201. walk->mTotalTime = 0;
  202. walk->mSubTime = 0;
  203. walk->mTotalInvokeCount = 0;
  204. }
  205. mCurrentProfilerData = mRootProfilerData;
  206. mCurrentProfilerData->mNextForRoot = 0;
  207. mCurrentProfilerData->mFirstChild = 0;
  208. for(U32 i = 0; i < ProfilerData::HashTableSize; i++)
  209. mCurrentProfilerData->mChildHash[i] = 0;
  210. mCurrentProfilerData->mInvokeCount = 0;
  211. mCurrentProfilerData->mTotalTime = 0;
  212. mCurrentProfilerData->mSubTime = 0;
  213. mCurrentProfilerData->mSubDepth = 0;
  214. mCurrentProfilerData->mLastSeenProfiler = 0;
  215. }
  216. static Profiler aProfiler; // allocate the global profiler
  217. ProfilerRootData::ProfilerRootData(const char *name)
  218. {
  219. for(ProfilerRootData *walk = sRootList; walk; walk = walk->mNextRoot)
  220. if(!dStrcmp(walk->mName, name))
  221. AssertFatal( false, avar( "Duplicate profile name: %s", name ) );
  222. mName = name;
  223. mNameHash = _StringTable::hashString(name);
  224. mNextRoot = sRootList;
  225. sRootList = this;
  226. mTotalTime = 0;
  227. mTotalInvokeCount = 0;
  228. mFirstProfilerData = NULL;
  229. mEnabled = true;
  230. }
  231. void Profiler::validate()
  232. {
  233. for(ProfilerRootData *walk = ProfilerRootData::sRootList; walk; walk = walk->mNextRoot)
  234. {
  235. for(ProfilerData *dp = walk->mFirstProfilerData; dp; dp = dp->mNextForRoot)
  236. {
  237. if(dp->mRoot != walk)
  238. Platform::debugBreak();
  239. // check if it's in the parent's list...
  240. ProfilerData *wk;
  241. for(wk = dp->mParent->mFirstChild; wk; wk = wk->mNextSibling)
  242. if(wk == dp)
  243. break;
  244. if(!wk)
  245. Platform::debugBreak();
  246. for(wk = dp->mParent->mChildHash[walk->mNameHash & (ProfilerData::HashTableSize - 1)] ;
  247. wk; wk = wk->mNextHash)
  248. if(wk == dp)
  249. break;
  250. if(!wk)
  251. Platform::debugBreak();
  252. }
  253. }
  254. }
  255. #ifdef TORQUE_ENABLE_PROFILE_PATH
  256. const char * Profiler::getProfilePath()
  257. {
  258. #ifdef TORQUE_MULTITHREAD
  259. // Ignore non-main-thread profiler activity.
  260. if( !ThreadManager::isMainThread() )
  261. return "[non-main thread]";
  262. #endif
  263. return (mEnabled && mCurrentProfilerData) ? mCurrentProfilerData->mPath : "na";
  264. }
  265. #endif
  266. #ifdef TORQUE_ENABLE_PROFILE_PATH
  267. const char * Profiler::constructProfilePath(ProfilerData * pd)
  268. {
  269. if (pd->mParent)
  270. {
  271. const bool saveEnable = gProfiler->mEnabled;
  272. gProfiler->mEnabled = false;
  273. const char * connector = " -> ";
  274. U32 len = dStrlen(pd->mParent->mPath);
  275. if (!len)
  276. connector = "";
  277. len += dStrlen(connector);
  278. len += dStrlen(pd->mRoot->mName);
  279. U32 mark = FrameAllocator::getWaterMark();
  280. char * buf = (char*)FrameAllocator::alloc(len+1);
  281. dStrcpy(buf,pd->mParent->mPath);
  282. dStrcat(buf,connector);
  283. dStrcat(buf,pd->mRoot->mName);
  284. const char * ret = StringTable->insert(buf);
  285. FrameAllocator::setWaterMark(mark);
  286. gProfiler->mEnabled = saveEnable;
  287. return ret;
  288. }
  289. return "root";
  290. }
  291. #endif
  292. void Profiler::hashPush(ProfilerRootData *root)
  293. {
  294. #ifdef TORQUE_MULTITHREAD
  295. // Ignore non-main-thread profiler activity.
  296. if( !ThreadManager::isMainThread() )
  297. return;
  298. #endif
  299. mStackDepth++;
  300. PROFILER_DEBUG_PUSH_NODE(root->mName);
  301. AssertFatal(mStackDepth <= mMaxStackDepth,
  302. "Stack overflow in profiler. You may have mismatched PROFILE_START and PROFILE_ENDs");
  303. if(!mEnabled)
  304. return;
  305. ProfilerData *nextProfiler = NULL;
  306. if(!root->mEnabled || mCurrentProfilerData->mRoot == root)
  307. {
  308. mCurrentProfilerData->mSubDepth++;
  309. return;
  310. }
  311. if(mCurrentProfilerData->mLastSeenProfiler &&
  312. mCurrentProfilerData->mLastSeenProfiler->mRoot == root)
  313. nextProfiler = mCurrentProfilerData->mLastSeenProfiler;
  314. if(!nextProfiler)
  315. {
  316. // first see if it's in the hash table...
  317. U32 index = root->mNameHash & (ProfilerData::HashTableSize - 1);
  318. nextProfiler = mCurrentProfilerData->mChildHash[index];
  319. while(nextProfiler)
  320. {
  321. if(nextProfiler->mRoot == root)
  322. break;
  323. nextProfiler = nextProfiler->mNextHash;
  324. }
  325. if(!nextProfiler)
  326. {
  327. nextProfiler = (ProfilerData *) malloc(sizeof(ProfilerData));
  328. for(U32 i = 0; i < ProfilerData::HashTableSize; i++)
  329. nextProfiler->mChildHash[i] = 0;
  330. nextProfiler->mRoot = root;
  331. nextProfiler->mNextForRoot = root->mFirstProfilerData;
  332. root->mFirstProfilerData = nextProfiler;
  333. nextProfiler->mNextProfilerData = mProfileList;
  334. mProfileList = nextProfiler;
  335. nextProfiler->mNextHash = mCurrentProfilerData->mChildHash[index];
  336. mCurrentProfilerData->mChildHash[index] = nextProfiler;
  337. nextProfiler->mParent = mCurrentProfilerData;
  338. nextProfiler->mNextSibling = mCurrentProfilerData->mFirstChild;
  339. mCurrentProfilerData->mFirstChild = nextProfiler;
  340. nextProfiler->mFirstChild = NULL;
  341. nextProfiler->mLastSeenProfiler = NULL;
  342. nextProfiler->mHash = root->mNameHash;
  343. nextProfiler->mInvokeCount = 0;
  344. nextProfiler->mTotalTime = 0;
  345. nextProfiler->mSubTime = 0;
  346. nextProfiler->mSubDepth = 0;
  347. #ifdef TORQUE_ENABLE_PROFILE_PATH
  348. nextProfiler->mPath = constructProfilePath(nextProfiler);
  349. #endif
  350. }
  351. }
  352. root->mTotalInvokeCount++;
  353. nextProfiler->mInvokeCount++;
  354. startHighResolutionTimer(nextProfiler->mStartTime);
  355. mCurrentProfilerData->mLastSeenProfiler = nextProfiler;
  356. mCurrentProfilerData = nextProfiler;
  357. }
  358. void Profiler::enable(bool enabled)
  359. {
  360. mNextEnable = enabled;
  361. }
  362. void Profiler::dumpToConsole()
  363. {
  364. mDumpToConsole = true;
  365. mDumpToFile = false;
  366. mDumpFileName[0] = '\0';
  367. }
  368. void Profiler::dumpToFile(const char* fileName)
  369. {
  370. AssertFatal(dStrlen(fileName) < DumpFileNameLength, "Error, dump filename too long");
  371. mDumpToFile = true;
  372. mDumpToConsole = false;
  373. dStrcpy(mDumpFileName, fileName);
  374. }
  375. void Profiler::hashPop(ProfilerRootData *expected)
  376. {
  377. #ifdef TORQUE_MULTITHREAD
  378. // Ignore non-main-thread profiler activity.
  379. if( !ThreadManager::isMainThread() )
  380. return;
  381. #endif
  382. mStackDepth--;
  383. PROFILER_DEBUG_POP_NODE();
  384. AssertFatal(mStackDepth >= 0, "Stack underflow in profiler. You may have mismatched PROFILE_START and PROFILE_ENDs");
  385. if(mEnabled)
  386. {
  387. if(mCurrentProfilerData->mSubDepth)
  388. {
  389. mCurrentProfilerData->mSubDepth--;
  390. return;
  391. }
  392. if(expected)
  393. {
  394. AssertISV(expected == mCurrentProfilerData->mRoot, "Profiler::hashPop - didn't get expected ProfilerRoot!");
  395. }
  396. F64 fElapsed = endHighResolutionTimer(mCurrentProfilerData->mStartTime);
  397. mCurrentProfilerData->mTotalTime += fElapsed;
  398. mCurrentProfilerData->mParent->mSubTime += fElapsed; // mark it in the parent as well...
  399. mCurrentProfilerData->mRoot->mTotalTime += fElapsed;
  400. if(mCurrentProfilerData->mParent->mRoot)
  401. mCurrentProfilerData->mParent->mRoot->mSubTime += fElapsed; // mark it in the parent as well...
  402. mCurrentProfilerData = mCurrentProfilerData->mParent;
  403. }
  404. if(mStackDepth == 0)
  405. {
  406. // apply the next enable...
  407. if(mDumpToConsole || mDumpToFile)
  408. {
  409. dump();
  410. startHighResolutionTimer(mCurrentProfilerData->mStartTime);
  411. }
  412. if(!mEnabled && mNextEnable)
  413. startHighResolutionTimer(mCurrentProfilerData->mStartTime);
  414. #if defined(TORQUE_OS_WIN)
  415. // The high performance counters under win32 are unreliable when running on multiple
  416. // processors. When the profiler is enabled, we restrict Torque to a single processor.
  417. if(mNextEnable != mEnabled)
  418. {
  419. if(mNextEnable)
  420. {
  421. Con::warnf("Warning: forcing the Torque profiler thread to run only on cpu 1.");
  422. SetThreadAffinityMask(GetCurrentThread(), 1);
  423. }
  424. else
  425. {
  426. Con::warnf("Warning: the Torque profiler thread may now run on any cpu.");
  427. DWORD_PTR procMask;
  428. DWORD_PTR sysMask;
  429. GetProcessAffinityMask( GetCurrentProcess(), &procMask, &sysMask);
  430. SetThreadAffinityMask( GetCurrentThread(), procMask);
  431. }
  432. }
  433. #endif
  434. mEnabled = mNextEnable;
  435. }
  436. }
  437. static S32 QSORT_CALLBACK rootDataCompare(const void *s1, const void *s2)
  438. {
  439. const ProfilerRootData *r1 = *((ProfilerRootData **) s1);
  440. const ProfilerRootData *r2 = *((ProfilerRootData **) s2);
  441. if((r2->mTotalTime - r2->mSubTime) > (r1->mTotalTime - r1->mSubTime))
  442. return 1;
  443. return -1;
  444. }
  445. static void profilerDataDumpRecurse(ProfilerData *data, char *buffer, U32 bufferLen, F64 totalTime)
  446. {
  447. // dump out this one:
  448. Con::printf("%7.3f %7.3f %8d %s%s",
  449. 100 * data->mTotalTime / totalTime,
  450. 100 * (data->mTotalTime - data->mSubTime) / totalTime,
  451. data->mInvokeCount,
  452. buffer,
  453. data->mRoot ? data->mRoot->mName : "ROOT" );
  454. data->mTotalTime = 0;
  455. data->mSubTime = 0;
  456. data->mInvokeCount = 0;
  457. buffer[bufferLen] = ' ';
  458. buffer[bufferLen+1] = ' ';
  459. buffer[bufferLen+2] = 0;
  460. // sort data's children...
  461. ProfilerData *list = NULL;
  462. while(data->mFirstChild)
  463. {
  464. ProfilerData *ins = data->mFirstChild;
  465. data->mFirstChild = ins->mNextSibling;
  466. ProfilerData **walk = &list;
  467. while(*walk && (*walk)->mTotalTime > ins->mTotalTime)
  468. walk = &(*walk)->mNextSibling;
  469. ins->mNextSibling = *walk;
  470. *walk = ins;
  471. }
  472. data->mFirstChild = list;
  473. while(list)
  474. {
  475. if(list->mInvokeCount)
  476. profilerDataDumpRecurse(list, buffer, bufferLen + 2, totalTime);
  477. list = list->mNextSibling;
  478. }
  479. buffer[bufferLen] = 0;
  480. }
  481. static void profilerDataDumpRecurseFile(ProfilerData *data, char *buffer, U32 bufferLen, F64 totalTime, FileStream& fws)
  482. {
  483. char pbuffer[256];
  484. dSprintf(pbuffer, 255, "%7.3f %7.3f %8d %s%s\n",
  485. 100 * data->mTotalTime / totalTime,
  486. 100 * (data->mTotalTime - data->mSubTime) / totalTime,
  487. data->mInvokeCount,
  488. buffer,
  489. data->mRoot ? data->mRoot->mName : "ROOT" );
  490. fws.write(dStrlen(pbuffer), pbuffer);
  491. data->mTotalTime = 0;
  492. data->mSubTime = 0;
  493. data->mInvokeCount = 0;
  494. buffer[bufferLen] = ' ';
  495. buffer[bufferLen+1] = ' ';
  496. buffer[bufferLen+2] = 0;
  497. // sort data's children...
  498. ProfilerData *list = NULL;
  499. while(data->mFirstChild)
  500. {
  501. ProfilerData *ins = data->mFirstChild;
  502. data->mFirstChild = ins->mNextSibling;
  503. ProfilerData **walk = &list;
  504. while(*walk && (*walk)->mTotalTime > ins->mTotalTime)
  505. walk = &(*walk)->mNextSibling;
  506. ins->mNextSibling = *walk;
  507. *walk = ins;
  508. }
  509. data->mFirstChild = list;
  510. while(list)
  511. {
  512. if(list->mInvokeCount)
  513. profilerDataDumpRecurseFile(list, buffer, bufferLen + 2, totalTime, fws);
  514. list = list->mNextSibling;
  515. }
  516. buffer[bufferLen] = 0;
  517. }
  518. void Profiler::dump()
  519. {
  520. bool enableSave = mEnabled;
  521. mEnabled = false;
  522. mStackDepth++;
  523. // may have some profiled calls... gotta turn em off.
  524. Vector<ProfilerRootData *> rootVector;
  525. F64 totalTime = 0;
  526. for(ProfilerRootData *walk = ProfilerRootData::sRootList; walk; walk = walk->mNextRoot)
  527. {
  528. totalTime += walk->mTotalTime - walk->mSubTime;
  529. rootVector.push_back(walk);
  530. }
  531. dQsort((void *) &rootVector[0], rootVector.size(), sizeof(ProfilerRootData *), rootDataCompare);
  532. if (mDumpToConsole == true)
  533. {
  534. Con::printf("Profiler Data Dump:");
  535. Con::printf("Ordered by non-sub total time -");
  536. Con::printf("%%NSTime %% Time Invoke # Name");
  537. for(U32 i = 0; i < rootVector.size(); i++)
  538. {
  539. Con::printf("%7.3f %7.3f %8d %s",
  540. 100 * (rootVector[i]->mTotalTime - rootVector[i]->mSubTime) / totalTime,
  541. 100 * rootVector[i]->mTotalTime / totalTime,
  542. rootVector[i]->mTotalInvokeCount,
  543. rootVector[i]->mName);
  544. rootVector[i]->mTotalInvokeCount = 0;
  545. rootVector[i]->mTotalTime = 0;
  546. rootVector[i]->mSubTime = 0;
  547. }
  548. Con::printf("");
  549. Con::printf("Ordered by stack trace total time -");
  550. Con::printf("%% Time %% NSTime Invoke # Name");
  551. mCurrentProfilerData->mTotalTime = endHighResolutionTimer(mCurrentProfilerData->mStartTime);
  552. char depthBuffer[MaxStackDepth * 2 + 1];
  553. depthBuffer[0] = 0;
  554. profilerDataDumpRecurse(mCurrentProfilerData, depthBuffer, 0, totalTime);
  555. mEnabled = enableSave;
  556. mStackDepth--;
  557. }
  558. else if (mDumpToFile == true && mDumpFileName[0] != '\0')
  559. {
  560. FileStream fws;
  561. bool success = fws.open(mDumpFileName, Torque::FS::File::Write);
  562. AssertFatal(success, "Cannot write profile dump to specified file!");
  563. char buffer[1024];
  564. dStrcpy(buffer, "Profiler Data Dump:\n");
  565. fws.write(dStrlen(buffer), buffer);
  566. dStrcpy(buffer, "Ordered by non-sub total time -\n");
  567. fws.write(dStrlen(buffer), buffer);
  568. dStrcpy(buffer, "%%NSTime %% Time Invoke # Name\n");
  569. fws.write(dStrlen(buffer), buffer);
  570. for(U32 i = 0; i < rootVector.size(); i++)
  571. {
  572. dSprintf(buffer, 1023, "%7.3f %7.3f %8d %s\n",
  573. 100 * (rootVector[i]->mTotalTime - rootVector[i]->mSubTime) / totalTime,
  574. 100 * rootVector[i]->mTotalTime / totalTime,
  575. rootVector[i]->mTotalInvokeCount,
  576. rootVector[i]->mName);
  577. fws.write(dStrlen(buffer), buffer);
  578. rootVector[i]->mTotalInvokeCount = 0;
  579. rootVector[i]->mTotalTime = 0;
  580. rootVector[i]->mSubTime = 0;
  581. }
  582. dStrcpy(buffer, "\nOrdered by non-sub total time -\n");
  583. fws.write(dStrlen(buffer), buffer);
  584. dStrcpy(buffer, "%%NSTime %% Time Invoke # Name\n");
  585. fws.write(dStrlen(buffer), buffer);
  586. mCurrentProfilerData->mTotalTime = endHighResolutionTimer(mCurrentProfilerData->mStartTime);
  587. char depthBuffer[MaxStackDepth * 2 + 1];
  588. depthBuffer[0] = 0;
  589. profilerDataDumpRecurseFile(mCurrentProfilerData, depthBuffer, 0, totalTime, fws);
  590. mEnabled = enableSave;
  591. mStackDepth--;
  592. fws.close();
  593. }
  594. mDumpToConsole = false;
  595. mDumpToFile = false;
  596. mDumpFileName[0] = '\0';
  597. }
  598. void Profiler::enableMarker(const char *marker, bool enable)
  599. {
  600. reset();
  601. U32 markerLen = dStrlen(marker);
  602. if(markerLen == 0)
  603. return;
  604. bool sn = marker[markerLen - 1] == '*';
  605. for(ProfilerRootData *data = ProfilerRootData::sRootList; data; data = data->mNextRoot)
  606. {
  607. if(sn)
  608. {
  609. if(!dStrncmp(marker, data->mName, markerLen - 1))
  610. data->mEnabled = enable;
  611. }
  612. else
  613. {
  614. if(!dStrcmp(marker, data->mName))
  615. data->mEnabled = enable;
  616. }
  617. }
  618. }
  619. //=============================================================================
  620. // Console Functions.
  621. //=============================================================================
  622. // MARK: ---- Console Functions ----
  623. //-----------------------------------------------------------------------------
  624. DefineEngineFunction( profilerMarkerEnable, void, ( const char* markerName, bool enable ), ( true ),
  625. "@brief Enable or disable a specific profile.\n\n"
  626. "@param enable Optional paramater to enable or disable the profile.\n"
  627. "@param markerName Name of a specific marker to enable or disable.\n"
  628. "@note Calling this function will first call profilerReset(), clearing all data from profiler. "
  629. "All profile markers are enabled by default.\n\n"
  630. "@ingroup Debugging")
  631. {
  632. if( gProfiler )
  633. gProfiler->enableMarker( markerName, enable );
  634. }
  635. //-----------------------------------------------------------------------------
  636. DefineEngineFunction( profilerEnable, void, ( bool enable ),,
  637. "@brief Enables or disables the profiler.\n\n"
  638. "Data is only gathered while the profiler is enabled.\n\n"
  639. "@note Profiler is not available in shipping builds.\n"
  640. "T3D has predefined profiling areas surrounded by markers, "
  641. "but you may need to define additional markers (in C++) around areas you wish to profile,"
  642. " by using the PROFILE_START( markerName ); and PROFILE_END(); macros.\n\n"
  643. "@ingroup Debugging\n" )
  644. {
  645. if(gProfiler)
  646. gProfiler->enable(enable);
  647. }
  648. DefineEngineFunction(profilerDump, void, (),,
  649. "@brief Dumps current profiling stats to the console window.\n\n"
  650. "@note Markers disabled with profilerMarkerEnable() will be skipped over. "
  651. "If the profiler is currently running, it will be disabled.\n"
  652. "@ingroup Debugging")
  653. {
  654. if(gProfiler)
  655. gProfiler->dumpToConsole();
  656. }
  657. DefineEngineFunction( profilerDumpToFile, void, ( const char* fileName ),,
  658. "@brief Dumps current profiling stats to a file.\n\n"
  659. "@note If the profiler is currently running, it will be disabled.\n"
  660. "@param fileName Name and path of file to save profiling stats to. Must use forward slashes (/). "
  661. "Will attempt to create the file if it does not already exist.\n"
  662. "@tsexample\n"
  663. "profilerDumpToFile( \"C:/Torque/log1.txt\" );\n"
  664. "@endtsexample\n\n"
  665. "@ingroup Debugging" )
  666. {
  667. if(gProfiler)
  668. gProfiler->dumpToFile(fileName);
  669. }
  670. DefineEngineFunction( profilerReset, void, (),,
  671. "@brief Resets the profiler, clearing it of all its data.\n\n"
  672. "If the profiler is currently running, it will first be disabled. "
  673. "All markers will retain their current enabled/disabled status.\n\n"
  674. "@ingroup Debugging" )
  675. {
  676. if(gProfiler)
  677. gProfiler->reset();
  678. }
  679. #endif