profiler.cpp 23 KB

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