profiler.cpp 23 KB

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