microprofile.h 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593
  1. #pragma once
  2. // This is free and unencumbered software released into the public domain.
  3. // Anyone is free to copy, modify, publish, use, compile, sell, or
  4. // distribute this software, either in source code form or as a compiled
  5. // binary, for any purpose, commercial or non-commercial, and by any
  6. // means.
  7. // In jurisdictions that recognize copyright laws, the author or authors
  8. // of this software dedicate any and all copyright interest in the
  9. // software to the public domain. We make this dedication for the benefit
  10. // of the public at large and to the detriment of our heirs and
  11. // successors. We intend this dedication to be an overt act of
  12. // relinquishment in perpetuity of all present and future rights to this
  13. // software under copyright law.
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  17. // IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  18. // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  19. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  20. // OTHER DEALINGS IN THE SOFTWARE.
  21. // For more information, please refer to <http://unlicense.org/>
  22. //
  23. // ***********************************************************************
  24. //
  25. //
  26. //
  27. //
  28. // Howto:
  29. // Call these functions from your code:
  30. // MicroProfileOnThreadCreate
  31. // MicroProfileMouseButton
  32. // MicroProfileMousePosition
  33. // MicroProfileModKey
  34. // MicroProfileFlip <-- Call this once per frame
  35. // MicroProfileDraw <-- Call this once per frame
  36. // MicroProfileToggleDisplayMode <-- Bind to a key to toggle profiling
  37. // MicroProfileTogglePause <-- Bind to a key to toggle pause
  38. //
  39. // Use these macros in your code in blocks you want to time:
  40. //
  41. // MICROPROFILE_DECLARE
  42. // MICROPROFILE_DEFINE
  43. // MICROPROFILE_DECLARE_GPU
  44. // MICROPROFILE_DEFINE_GPU
  45. // MICROPROFILE_SCOPE
  46. // MICROPROFILE_SCOPEI
  47. // MICROPROFILE_SCOPEGPU
  48. // MICROPROFILE_SCOPEGPUI
  49. // MICROPROFILE_META
  50. //
  51. //
  52. // Usage:
  53. //
  54. // {
  55. // MICROPROFILE_SCOPEI("GroupName", "TimerName", nColorRgb):
  56. // ..Code to be timed..
  57. // }
  58. //
  59. // MICROPROFILE_DECLARE / MICROPROFILE_DEFINE allows defining groups in a shared place, to ensure sorting of the timers
  60. //
  61. // (in global scope)
  62. // MICROPROFILE_DEFINE(g_ProfileFisk, "Fisk", "Skalle", nSomeColorRgb);
  63. //
  64. // (in some other file)
  65. // MICROPROFILE_DECLARE(g_ProfileFisk);
  66. //
  67. // void foo(){
  68. // MICROPROFILE_SCOPE(g_ProfileFisk);
  69. // }
  70. //
  71. // Once code is instrumented the gui is activeted by calling MicroProfileToggleDisplayMode or by clicking in the upper left corner of
  72. // the screen
  73. //
  74. // The following functions must be implemented before the profiler is usable
  75. // debug render:
  76. // void MicroProfileDrawText(int nX, int nY, uint32_t nColor, const char* pText, uint32_t nNumCharacters);
  77. // void MicroProfileDrawBox(int nX, int nY, int nX1, int nY1, uint32_t nColor, MicroProfileBoxType = MicroProfileBoxTypeFlat);
  78. // void MicroProfileDrawLine2D(uint32_t nVertices, float* pVertices, uint32_t nColor);
  79. // Gpu time stamps: (See below for d3d/opengl helper)
  80. // uint32_t MicroProfileGpuInsertTimeStamp();
  81. // uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey);
  82. // uint64_t MicroProfileTicksPerSecondGpu();
  83. // threading:
  84. // const char* MicroProfileGetThreadName(); Threadnames in detailed view
  85. //
  86. // Default implementations of Gpu timestamp functions:
  87. // Opengl:
  88. // in .c file where MICROPROFILE_IMPL is defined:
  89. // #define MICROPROFILE_GPU_TIMERS_GL
  90. // call MicroProfileGpuInitGL() on startup
  91. // D3D11:
  92. // in .c file where MICROPROFILE_IMPL is defined:
  93. // #define MICROPROFILE_GPU_TIMERS_D3D11
  94. // call MICROPROFILE_GPU_TIMERS_D3D11(). Pass Device & ImmediateContext
  95. //
  96. // Limitations:
  97. // GPU timestamps can only be inserted from one thread.
  98. #ifndef MICROPROFILE_ENABLED
  99. #define MICROPROFILE_ENABLED 1
  100. #endif
  101. #include <stdint.h>
  102. typedef uint64_t MicroProfileToken;
  103. typedef uint16_t MicroProfileGroupId;
  104. #if 0 == MICROPROFILE_ENABLED
  105. #define MICROPROFILE_DECLARE(var)
  106. #define MICROPROFILE_DEFINE(var, group, name, color)
  107. #define MICROPROFILE_REGISTER_GROUP(group, color, category)
  108. #define MICROPROFILE_DECLARE_GPU(var)
  109. #define MICROPROFILE_DEFINE_GPU(var, name, color)
  110. #define MICROPROFILE_SCOPE(var) do{}while(0)
  111. #define MICROPROFILE_SCOPEI(group, name, color) do{}while(0)
  112. #define MICROPROFILE_SCOPEGPU(var) do{}while(0)
  113. #define MICROPROFILE_SCOPEGPUI( name, color) do{}while(0)
  114. #define MICROPROFILE_META_CPU(name, count)
  115. #define MICROPROFILE_META_GPU(name, count)
  116. #define MICROPROFILE_FORCEENABLECPUGROUP(s) do{} while(0)
  117. #define MICROPROFILE_FORCEDISABLECPUGROUP(s) do{} while(0)
  118. #define MICROPROFILE_FORCEENABLEGPUGROUP(s) do{} while(0)
  119. #define MICROPROFILE_FORCEDISABLEGPUGROUP(s) do{} while(0)
  120. #define MICROPROFILE_SCOPE_TOKEN(token)
  121. #define MicroProfileGetTime(group, name) 0.f
  122. #define MicroProfileOnThreadCreate(foo) do{}while(0)
  123. #define MicroProfileFlip() do{}while(0)
  124. #define MicroProfileSetAggregateFrames(a) do{}while(0)
  125. #define MicroProfileGetAggregateFrames() 0
  126. #define MicroProfileGetCurrentAggregateFrames() 0
  127. #define MicroProfileTogglePause() do{}while(0)
  128. #define MicroProfileToggleAllGroups() do{} while(0)
  129. #define MicroProfileDumpTimers() do{}while(0)
  130. #define MicroProfileShutdown() do{}while(0)
  131. #define MicroProfileSetForceEnable(a) do{} while(0)
  132. #define MicroProfileGetForceEnable() false
  133. #define MicroProfileSetEnableAllGroups(a) do{} while(0)
  134. #define MicroProfileEnableCategory(a) do{} while(0)
  135. #define MicroProfileDisableCategory(a) do{} while(0)
  136. #define MicroProfileGetEnableAllGroups() false
  137. #define MicroProfileSetForceMetaCounters(a)
  138. #define MicroProfileGetForceMetaCounters() 0
  139. #define MicroProfileEnableMetaCounter(c) do{}while(0)
  140. #define MicroProfileDisableMetaCounter(c) do{}while(0)
  141. #define MicroProfileDumpFile(html,csv) do{} while(0)
  142. #define MicroProfileWebServerPort() ((uint32_t)-1)
  143. #else
  144. #include <stdint.h>
  145. #include <string.h>
  146. #include <algorithm>
  147. #include <array>
  148. #include <atomic>
  149. #include <mutex>
  150. #include <thread>
  151. #ifndef MICROPROFILE_API
  152. #define MICROPROFILE_API
  153. #endif
  154. MICROPROFILE_API int64_t MicroProfileTicksPerSecondCpu();
  155. #if defined(__APPLE__)
  156. #include <mach/mach.h>
  157. #include <mach/mach_time.h>
  158. #include <unistd.h>
  159. #include <libkern/OSAtomic.h>
  160. #include <TargetConditionals.h>
  161. #if TARGET_OS_IPHONE
  162. #define MICROPROFILE_IOS
  163. #endif
  164. #define MP_TICK() mach_absolute_time()
  165. inline int64_t MicroProfileTicksPerSecondCpu()
  166. {
  167. static int64_t nTicksPerSecond = 0;
  168. if(nTicksPerSecond == 0)
  169. {
  170. mach_timebase_info_data_t sTimebaseInfo;
  171. mach_timebase_info(&sTimebaseInfo);
  172. nTicksPerSecond = 1000000000ll * sTimebaseInfo.denom / sTimebaseInfo.numer;
  173. }
  174. return nTicksPerSecond;
  175. }
  176. inline uint64_t MicroProfileGetCurrentThreadId()
  177. {
  178. uint64_t tid;
  179. pthread_threadid_np(pthread_self(), &tid);
  180. return tid;
  181. }
  182. #define MP_BREAK() __builtin_trap()
  183. #define MP_THREAD_LOCAL __thread
  184. #define MP_STRCASECMP strcasecmp
  185. #define MP_GETCURRENTTHREADID() MicroProfileGetCurrentThreadId()
  186. typedef uint64_t ThreadIdType;
  187. #elif defined(_WIN32)
  188. int64_t MicroProfileGetTick();
  189. #define MP_TICK() MicroProfileGetTick()
  190. #define MP_BREAK() __debugbreak()
  191. #define MP_THREAD_LOCAL thread_local
  192. #define MP_STRCASECMP _stricmp
  193. #define MP_GETCURRENTTHREADID() GetCurrentThreadId()
  194. typedef uint32_t ThreadIdType;
  195. #elif !defined(_WIN32)
  196. #include <unistd.h>
  197. #include <time.h>
  198. inline int64_t MicroProfileTicksPerSecondCpu()
  199. {
  200. return 1000000000ll;
  201. }
  202. inline int64_t MicroProfileGetTick()
  203. {
  204. timespec ts;
  205. clock_gettime(CLOCK_REALTIME, &ts);
  206. return 1000000000ll * ts.tv_sec + ts.tv_nsec;
  207. }
  208. #define MP_TICK() MicroProfileGetTick()
  209. #define MP_BREAK() __builtin_trap()
  210. #define MP_THREAD_LOCAL __thread
  211. #define MP_STRCASECMP strcasecmp
  212. #define MP_GETCURRENTTHREADID() (uint64_t)pthread_self()
  213. typedef uint64_t ThreadIdType;
  214. #endif
  215. #ifndef MP_GETCURRENTTHREADID
  216. #define MP_GETCURRENTTHREADID() 0
  217. typedef uint32_t ThreadIdType;
  218. #endif
  219. #define MP_ASSERT(a) do{if(!(a)){MP_BREAK();} }while(0)
  220. #define MICROPROFILE_DECLARE(var) extern MicroProfileToken g_mp_##var
  221. #define MICROPROFILE_DEFINE(var, group, name, color) MicroProfileToken g_mp_##var = MicroProfileGetToken(group, name, color, MicroProfileTokenTypeCpu)
  222. #define MICROPROFILE_REGISTER_GROUP(group, category, color) MicroProfileRegisterGroup(group, category, color)
  223. #define MICROPROFILE_DECLARE_GPU(var) extern MicroProfileToken g_mp_##var
  224. #define MICROPROFILE_DEFINE_GPU(var, name, color) MicroProfileToken g_mp_##var = MicroProfileGetToken("GPU", name, color, MicroProfileTokenTypeGpu)
  225. #define MICROPROFILE_TOKEN_PASTE0(a, b) a ## b
  226. #define MICROPROFILE_TOKEN_PASTE(a, b) MICROPROFILE_TOKEN_PASTE0(a,b)
  227. #define MICROPROFILE_TOKEN(var) g_mp_##var
  228. #define MICROPROFILE_SCOPE(var) MicroProfileScopeHandler MICROPROFILE_TOKEN_PASTE(foo, __LINE__)(g_mp_##var)
  229. #define MICROPROFILE_SCOPE_TOKEN(token) MicroProfileScopeHandler MICROPROFILE_TOKEN_PASTE(foo, __LINE__)(token)
  230. #define MICROPROFILE_SCOPEI(group, name, color) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__) = MicroProfileGetToken(group, name, color, MicroProfileTokenTypeCpu); MicroProfileScopeHandler MICROPROFILE_TOKEN_PASTE(foo,__LINE__)( MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__))
  231. #define MICROPROFILE_SCOPEGPU(var) MicroProfileScopeGpuHandler MICROPROFILE_TOKEN_PASTE(foo, __LINE__)(g_mp_##var)
  232. #define MICROPROFILE_SCOPEGPUI(name, color) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__) = MicroProfileGetToken("GPU", name, color, MicroProfileTokenTypeGpu); MicroProfileScopeGpuHandler MICROPROFILE_TOKEN_PASTE(foo,__LINE__)( MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__))
  233. #define MICROPROFILE_META_CPU(name, count) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__) = MicroProfileGetMetaToken(name); MicroProfileMetaUpdate(MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__), count, MicroProfileTokenTypeCpu)
  234. #define MICROPROFILE_META_GPU(name, count) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__) = MicroProfileGetMetaToken(name); MicroProfileMetaUpdate(MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__), count, MicroProfileTokenTypeGpu)
  235. #ifndef MICROPROFILE_USE_THREAD_NAME_CALLBACK
  236. #define MICROPROFILE_USE_THREAD_NAME_CALLBACK 0
  237. #endif
  238. #ifndef MICROPROFILE_PER_THREAD_BUFFER_SIZE
  239. #define MICROPROFILE_PER_THREAD_BUFFER_SIZE (2048<<10)
  240. #endif
  241. #ifndef MICROPROFILE_MAX_FRAME_HISTORY
  242. #define MICROPROFILE_MAX_FRAME_HISTORY 512
  243. #endif
  244. #ifndef MICROPROFILE_PRINTF
  245. #define MICROPROFILE_PRINTF printf
  246. #endif
  247. #ifndef MICROPROFILE_META_MAX
  248. #define MICROPROFILE_META_MAX 8
  249. #endif
  250. #ifndef MICROPROFILE_WEBSERVER_PORT
  251. #define MICROPROFILE_WEBSERVER_PORT 1338
  252. #endif
  253. #ifndef MICROPROFILE_WEBSERVER
  254. #define MICROPROFILE_WEBSERVER 1
  255. #endif
  256. #ifndef MICROPROFILE_WEBSERVER_MAXFRAMES
  257. #define MICROPROFILE_WEBSERVER_MAXFRAMES 30
  258. #endif
  259. #ifndef MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE
  260. #define MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE (16<<10)
  261. #endif
  262. #ifndef MICROPROFILE_GPU_TIMERS
  263. #define MICROPROFILE_GPU_TIMERS 1
  264. #endif
  265. #ifndef MICROPROFILE_GPU_FRAME_DELAY
  266. #define MICROPROFILE_GPU_FRAME_DELAY 3 //must be > 0
  267. #endif
  268. #ifndef MICROPROFILE_NAME_MAX_LEN
  269. #define MICROPROFILE_NAME_MAX_LEN 64
  270. #endif
  271. #define MICROPROFILE_FORCEENABLECPUGROUP(s) MicroProfileForceEnableGroup(s, MicroProfileTokenTypeCpu)
  272. #define MICROPROFILE_FORCEDISABLECPUGROUP(s) MicroProfileForceDisableGroup(s, MicroProfileTokenTypeCpu)
  273. #define MICROPROFILE_FORCEENABLEGPUGROUP(s) MicroProfileForceEnableGroup(s, MicroProfileTokenTypeGpu)
  274. #define MICROPROFILE_FORCEDISABLEGPUGROUP(s) MicroProfileForceDisableGroup(s, MicroProfileTokenTypeGpu)
  275. #define MICROPROFILE_INVALID_TICK ((uint64_t)-1)
  276. #define MICROPROFILE_GROUP_MASK_ALL 0xffffffffffff
  277. #define MICROPROFILE_INVALID_TOKEN (uint64_t)-1
  278. enum MicroProfileTokenType
  279. {
  280. MicroProfileTokenTypeCpu,
  281. MicroProfileTokenTypeGpu,
  282. };
  283. enum MicroProfileBoxType
  284. {
  285. MicroProfileBoxTypeBar,
  286. MicroProfileBoxTypeFlat,
  287. };
  288. struct MicroProfile;
  289. MICROPROFILE_API void MicroProfileInit();
  290. MICROPROFILE_API void MicroProfileShutdown();
  291. MICROPROFILE_API MicroProfileToken MicroProfileFindToken(const char* sGroup, const char* sName);
  292. MICROPROFILE_API MicroProfileToken MicroProfileGetToken(const char* sGroup, const char* sName, uint32_t nColor, MicroProfileTokenType Token = MicroProfileTokenTypeCpu);
  293. MICROPROFILE_API MicroProfileToken MicroProfileGetMetaToken(const char* pName);
  294. MICROPROFILE_API void MicroProfileMetaUpdate(MicroProfileToken, int nCount, MicroProfileTokenType eTokenType);
  295. MICROPROFILE_API uint64_t MicroProfileEnter(MicroProfileToken nToken);
  296. MICROPROFILE_API void MicroProfileLeave(MicroProfileToken nToken, uint64_t nTick);
  297. MICROPROFILE_API uint64_t MicroProfileGpuEnter(MicroProfileToken nToken);
  298. MICROPROFILE_API void MicroProfileGpuLeave(MicroProfileToken nToken, uint64_t nTick);
  299. inline uint16_t MicroProfileGetTimerIndex(MicroProfileToken t){ return (t&0xffff); }
  300. inline uint64_t MicroProfileGetGroupMask(MicroProfileToken t){ return ((t>>16)&MICROPROFILE_GROUP_MASK_ALL);}
  301. inline MicroProfileToken MicroProfileMakeToken(uint64_t nGroupMask, uint16_t nTimer){ return (nGroupMask<<16) | nTimer;}
  302. MICROPROFILE_API void MicroProfileFlip(); //! call once per frame.
  303. MICROPROFILE_API void MicroProfileTogglePause();
  304. MICROPROFILE_API void MicroProfileForceEnableGroup(const char* pGroup, MicroProfileTokenType Type);
  305. MICROPROFILE_API void MicroProfileForceDisableGroup(const char* pGroup, MicroProfileTokenType Type);
  306. MICROPROFILE_API float MicroProfileGetTime(const char* pGroup, const char* pName);
  307. MICROPROFILE_API void MicroProfileContextSwitchSearch(uint32_t* pContextSwitchStart, uint32_t* pContextSwitchEnd, uint64_t nBaseTicksCpu, uint64_t nBaseTicksEndCpu);
  308. MICROPROFILE_API void MicroProfileOnThreadCreate(const char* pThreadName); //should be called from newly created threads
  309. MICROPROFILE_API void MicroProfileOnThreadExit(); //call on exit to reuse log
  310. MICROPROFILE_API void MicroProfileInitThreadLog();
  311. MICROPROFILE_API void MicroProfileSetForceEnable(bool bForceEnable);
  312. MICROPROFILE_API bool MicroProfileGetForceEnable();
  313. MICROPROFILE_API void MicroProfileSetEnableAllGroups(bool bEnable);
  314. MICROPROFILE_API void MicroProfileEnableCategory(const char* pCategory);
  315. MICROPROFILE_API void MicroProfileDisableCategory(const char* pCategory);
  316. MICROPROFILE_API bool MicroProfileGetEnableAllGroups();
  317. MICROPROFILE_API void MicroProfileSetForceMetaCounters(bool bEnable);
  318. MICROPROFILE_API bool MicroProfileGetForceMetaCounters();
  319. MICROPROFILE_API void MicroProfileEnableMetaCounter(const char* pMet);
  320. MICROPROFILE_API void MicroProfileDisableMetaCounter(const char* pMet);
  321. MICROPROFILE_API void MicroProfileSetAggregateFrames(int frames);
  322. MICROPROFILE_API int MicroProfileGetAggregateFrames();
  323. MICROPROFILE_API int MicroProfileGetCurrentAggregateFrames();
  324. MICROPROFILE_API MicroProfile* MicroProfileGet();
  325. MICROPROFILE_API void MicroProfileGetRange(uint32_t nPut, uint32_t nGet, uint32_t nRange[2][2]);
  326. MICROPROFILE_API std::recursive_mutex& MicroProfileGetMutex();
  327. MICROPROFILE_API void MicroProfileStartContextSwitchTrace();
  328. MICROPROFILE_API void MicroProfileStopContextSwitchTrace();
  329. MICROPROFILE_API bool MicroProfileIsLocalThread(uint32_t nThreadId);
  330. #if MICROPROFILE_WEBSERVER
  331. MICROPROFILE_API void MicroProfileDumpFile(const char* pHtml, const char* pCsv);
  332. MICROPROFILE_API uint32_t MicroProfileWebServerPort();
  333. #else
  334. #define MicroProfileDumpFile(c) do{} while(0)
  335. #define MicroProfileWebServerPort() ((uint32_t)-1)
  336. #endif
  337. #if MICROPROFILE_GPU_TIMERS
  338. MICROPROFILE_API uint32_t MicroProfileGpuInsertTimeStamp();
  339. MICROPROFILE_API uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey);
  340. MICROPROFILE_API uint64_t MicroProfileTicksPerSecondGpu();
  341. MICROPROFILE_API int MicroProfileGetGpuTickReference(int64_t* pOutCPU, int64_t* pOutGpu);
  342. #else
  343. #define MicroProfileGpuInsertTimeStamp() 1
  344. #define MicroProfileGpuGetTimeStamp(a) 0
  345. #define MicroProfileTicksPerSecondGpu() 1
  346. #define MicroProfileGetGpuTickReference(a,b) 0
  347. #endif
  348. #if MICROPROFILE_GPU_TIMERS_D3D11
  349. #define MICROPROFILE_D3D_MAX_QUERIES (8<<10)
  350. MICROPROFILE_API void MicroProfileGpuInitD3D11(void* pDevice, void* pDeviceContext);
  351. #endif
  352. #if MICROPROFILE_GPU_TIMERS_GL
  353. #define MICROPROFILE_GL_MAX_QUERIES (8<<10)
  354. MICROPROFILE_API void MicroProfileGpuInitGL();
  355. #endif
  356. #if MICROPROFILE_USE_THREAD_NAME_CALLBACK
  357. MICROPROFILE_API const char* MicroProfileGetThreadName();
  358. #else
  359. #define MicroProfileGetThreadName() "<implement MicroProfileGetThreadName to get threadnames>"
  360. #endif
  361. #if !defined(MICROPROFILE_THREAD_NAME_FROM_ID)
  362. #define MICROPROFILE_THREAD_NAME_FROM_ID(a) ""
  363. #endif
  364. struct MicroProfileScopeHandler
  365. {
  366. MicroProfileToken nToken;
  367. uint64_t nTick;
  368. MicroProfileScopeHandler(MicroProfileToken Token):nToken(Token)
  369. {
  370. nTick = MicroProfileEnter(nToken);
  371. }
  372. ~MicroProfileScopeHandler()
  373. {
  374. MicroProfileLeave(nToken, nTick);
  375. }
  376. };
  377. struct MicroProfileScopeGpuHandler
  378. {
  379. MicroProfileToken nToken;
  380. uint64_t nTick;
  381. MicroProfileScopeGpuHandler(MicroProfileToken Token):nToken(Token)
  382. {
  383. nTick = MicroProfileGpuEnter(nToken);
  384. }
  385. ~MicroProfileScopeGpuHandler()
  386. {
  387. MicroProfileGpuLeave(nToken, nTick);
  388. }
  389. };
  390. #define MICROPROFILE_MAX_TIMERS 1024
  391. #define MICROPROFILE_MAX_GROUPS 48 //dont bump! no. of bits used it bitmask
  392. #define MICROPROFILE_MAX_CATEGORIES 16
  393. #define MICROPROFILE_MAX_GRAPHS 5
  394. #define MICROPROFILE_GRAPH_HISTORY 128
  395. #define MICROPROFILE_BUFFER_SIZE ((MICROPROFILE_PER_THREAD_BUFFER_SIZE)/sizeof(MicroProfileLogEntry))
  396. #define MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS 256
  397. #define MICROPROFILE_STACK_MAX 32
  398. //#define MICROPROFILE_MAX_PRESETS 5
  399. #define MICROPROFILE_ANIM_DELAY_PRC 0.5f
  400. #define MICROPROFILE_GAP_TIME 50 //extra ms to fetch to close timers from earlier frames
  401. #ifndef MICROPROFILE_MAX_THREADS
  402. #define MICROPROFILE_MAX_THREADS 32
  403. #endif
  404. #ifndef MICROPROFILE_UNPACK_RED
  405. #define MICROPROFILE_UNPACK_RED(c) ((c)>>16)
  406. #endif
  407. #ifndef MICROPROFILE_UNPACK_GREEN
  408. #define MICROPROFILE_UNPACK_GREEN(c) ((c)>>8)
  409. #endif
  410. #ifndef MICROPROFILE_UNPACK_BLUE
  411. #define MICROPROFILE_UNPACK_BLUE(c) ((c))
  412. #endif
  413. #ifndef MICROPROFILE_DEFAULT_PRESET
  414. #define MICROPROFILE_DEFAULT_PRESET "Default"
  415. #endif
  416. #ifndef MICROPROFILE_CONTEXT_SWITCH_TRACE
  417. #if defined(_WIN32)
  418. #define MICROPROFILE_CONTEXT_SWITCH_TRACE 1
  419. #elif defined(__APPLE__)
  420. #define MICROPROFILE_CONTEXT_SWITCH_TRACE 0 //disabled until dtrace script is working.
  421. #else
  422. #define MICROPROFILE_CONTEXT_SWITCH_TRACE 0
  423. #endif
  424. #endif
  425. #if MICROPROFILE_CONTEXT_SWITCH_TRACE
  426. #define MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE (128*1024) //2mb with 16 byte entry size
  427. #else
  428. #define MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE (1)
  429. #endif
  430. #ifndef MICROPROFILE_MINIZ
  431. #define MICROPROFILE_MINIZ 0
  432. #endif
  433. #ifdef _WIN32
  434. #include <basetsd.h>
  435. typedef UINT_PTR MpSocket;
  436. #else
  437. typedef int MpSocket;
  438. #endif
  439. #ifndef _WIN32
  440. typedef pthread_t MicroProfileThread;
  441. #elif defined(_MSC_VER)
  442. typedef HANDLE MicroProfileThread;
  443. #else
  444. typedef std::thread* MicroProfileThread;
  445. #endif
  446. enum MicroProfileDrawMask
  447. {
  448. MP_DRAW_OFF = 0x0,
  449. MP_DRAW_BARS = 0x1,
  450. MP_DRAW_DETAILED = 0x2,
  451. MP_DRAW_HIDDEN = 0x3,
  452. };
  453. enum MicroProfileDrawBarsMask
  454. {
  455. MP_DRAW_TIMERS = 0x1,
  456. MP_DRAW_AVERAGE = 0x2,
  457. MP_DRAW_MAX = 0x4,
  458. MP_DRAW_CALL_COUNT = 0x8,
  459. MP_DRAW_TIMERS_EXCLUSIVE = 0x10,
  460. MP_DRAW_AVERAGE_EXCLUSIVE = 0x20,
  461. MP_DRAW_MAX_EXCLUSIVE = 0x40,
  462. MP_DRAW_META_FIRST = 0x80,
  463. MP_DRAW_ALL = 0xffffffff,
  464. };
  465. typedef uint64_t MicroProfileLogEntry;
  466. struct MicroProfileTimer
  467. {
  468. uint64_t nTicks;
  469. uint32_t nCount;
  470. };
  471. struct MicroProfileCategory
  472. {
  473. char pName[MICROPROFILE_NAME_MAX_LEN];
  474. uint64_t nGroupMask;
  475. };
  476. struct MicroProfileGroupInfo
  477. {
  478. char pName[MICROPROFILE_NAME_MAX_LEN];
  479. uint32_t nNameLen;
  480. uint32_t nGroupIndex;
  481. uint32_t nNumTimers;
  482. uint32_t nMaxTimerNameLen;
  483. uint32_t nColor;
  484. uint32_t nCategory;
  485. MicroProfileTokenType Type;
  486. };
  487. struct MicroProfileTimerInfo
  488. {
  489. MicroProfileToken nToken;
  490. uint32_t nTimerIndex;
  491. uint32_t nGroupIndex;
  492. char pName[MICROPROFILE_NAME_MAX_LEN];
  493. uint32_t nNameLen;
  494. uint32_t nColor;
  495. bool bGraph;
  496. };
  497. struct MicroProfileGraphState
  498. {
  499. int64_t nHistory[MICROPROFILE_GRAPH_HISTORY];
  500. MicroProfileToken nToken;
  501. int32_t nKey;
  502. };
  503. struct MicroProfileContextSwitch
  504. {
  505. ThreadIdType nThreadOut;
  506. ThreadIdType nThreadIn;
  507. int64_t nCpu : 8;
  508. int64_t nTicks : 56;
  509. };
  510. struct MicroProfileFrameState
  511. {
  512. int64_t nFrameStartCpu;
  513. int64_t nFrameStartGpu;
  514. uint32_t nLogStart[MICROPROFILE_MAX_THREADS];
  515. };
  516. struct MicroProfileThreadLog
  517. {
  518. std::array<MicroProfileLogEntry, MICROPROFILE_BUFFER_SIZE> Log{};
  519. std::atomic<uint32_t> nPut{0};
  520. std::atomic<uint32_t> nGet{0};
  521. uint32_t nActive = 0;
  522. uint32_t nGpu = 0;
  523. ThreadIdType nThreadId{};
  524. std::array<uint32_t, MICROPROFILE_STACK_MAX> nStack{};
  525. std::array<int64_t, MICROPROFILE_STACK_MAX> nChildTickStack{};
  526. uint32_t nStackPos = 0;
  527. std::array<uint8_t, MICROPROFILE_MAX_GROUPS> nGroupStackPos{};
  528. std::array<int64_t, MICROPROFILE_MAX_GROUPS> nGroupTicks{};
  529. std::array<int64_t, MICROPROFILE_MAX_GROUPS> nAggregateGroupTicks{};
  530. enum
  531. {
  532. THREAD_MAX_LEN = 64,
  533. };
  534. char ThreadName[64]{};
  535. int nFreeListNext = 0;
  536. void Reset() {
  537. Log.fill({});
  538. nPut = 0;
  539. nGet = 0;
  540. nActive = 0;
  541. nGpu = 0;
  542. nThreadId = {};
  543. nStack.fill(0);
  544. nChildTickStack.fill(0);
  545. nStackPos = 0;
  546. nGroupStackPos.fill(0);
  547. nGroupTicks.fill(0);
  548. nAggregateGroupTicks.fill(0);
  549. std::fill(std::begin(ThreadName), std::end(ThreadName), '\0');
  550. nFreeListNext = 0;
  551. }
  552. };
  553. #if MICROPROFILE_GPU_TIMERS_D3D11
  554. struct MicroProfileD3D11Frame
  555. {
  556. uint32_t m_nQueryStart;
  557. uint32_t m_nQueryCount;
  558. uint32_t m_nRateQueryStarted;
  559. void* m_pRateQuery;
  560. };
  561. struct MicroProfileGpuTimerState
  562. {
  563. uint32_t bInitialized;
  564. void* m_pDevice;
  565. void* m_pDeviceContext;
  566. void* m_pQueries[MICROPROFILE_D3D_MAX_QUERIES];
  567. int64_t m_nQueryResults[MICROPROFILE_D3D_MAX_QUERIES];
  568. uint32_t m_nQueryPut;
  569. uint32_t m_nQueryGet;
  570. uint32_t m_nQueryFrame;
  571. int64_t m_nQueryFrequency;
  572. MicroProfileD3D11Frame m_QueryFrames[MICROPROFILE_GPU_FRAME_DELAY];
  573. };
  574. #elif MICROPROFILE_GPU_TIMERS_GL
  575. struct MicroProfileGpuTimerState
  576. {
  577. uint32_t GLTimers[MICROPROFILE_GL_MAX_QUERIES];
  578. uint32_t GLTimerPos;
  579. };
  580. #else
  581. struct MicroProfileGpuTimerState{};
  582. #endif
  583. struct MicroProfile
  584. {
  585. uint32_t nTotalTimers;
  586. uint32_t nGroupCount;
  587. uint32_t nCategoryCount;
  588. uint32_t nAggregateClear;
  589. uint32_t nAggregateFlip;
  590. uint32_t nAggregateFlipCount;
  591. uint32_t nAggregateFrames;
  592. uint64_t nAggregateFlipTick;
  593. uint32_t nDisplay;
  594. uint32_t nBars;
  595. uint64_t nActiveGroup;
  596. uint32_t nActiveBars;
  597. uint64_t nForceGroup;
  598. uint32_t nForceEnable;
  599. uint32_t nForceMetaCounters;
  600. uint64_t nForceGroupUI;
  601. uint64_t nActiveGroupWanted;
  602. uint32_t nAllGroupsWanted;
  603. uint32_t nAllThreadsWanted;
  604. uint32_t nOverflow;
  605. uint64_t nGroupMask;
  606. uint32_t nRunning;
  607. uint32_t nToggleRunning;
  608. uint32_t nMaxGroupSize;
  609. uint32_t nDumpFileNextFrame;
  610. uint32_t nAutoClearFrames;
  611. char HtmlDumpPath[512];
  612. char CsvDumpPath[512];
  613. int64_t nPauseTicks;
  614. float fReferenceTime;
  615. float fRcpReferenceTime;
  616. MicroProfileCategory CategoryInfo[MICROPROFILE_MAX_CATEGORIES];
  617. MicroProfileGroupInfo GroupInfo[MICROPROFILE_MAX_GROUPS];
  618. MicroProfileTimerInfo TimerInfo[MICROPROFILE_MAX_TIMERS];
  619. uint8_t TimerToGroup[MICROPROFILE_MAX_TIMERS];
  620. MicroProfileTimer AccumTimers[MICROPROFILE_MAX_TIMERS];
  621. uint64_t AccumMaxTimers[MICROPROFILE_MAX_TIMERS];
  622. uint64_t AccumTimersExclusive[MICROPROFILE_MAX_TIMERS];
  623. uint64_t AccumMaxTimersExclusive[MICROPROFILE_MAX_TIMERS];
  624. MicroProfileTimer Frame[MICROPROFILE_MAX_TIMERS];
  625. uint64_t FrameExclusive[MICROPROFILE_MAX_TIMERS];
  626. MicroProfileTimer Aggregate[MICROPROFILE_MAX_TIMERS];
  627. uint64_t AggregateMax[MICROPROFILE_MAX_TIMERS];
  628. uint64_t AggregateExclusive[MICROPROFILE_MAX_TIMERS];
  629. uint64_t AggregateMaxExclusive[MICROPROFILE_MAX_TIMERS];
  630. uint64_t FrameGroup[MICROPROFILE_MAX_GROUPS];
  631. uint64_t AccumGroup[MICROPROFILE_MAX_GROUPS];
  632. uint64_t AccumGroupMax[MICROPROFILE_MAX_GROUPS];
  633. uint64_t AggregateGroup[MICROPROFILE_MAX_GROUPS];
  634. uint64_t AggregateGroupMax[MICROPROFILE_MAX_GROUPS];
  635. struct
  636. {
  637. uint64_t nCounters[MICROPROFILE_MAX_TIMERS];
  638. uint64_t nAccum[MICROPROFILE_MAX_TIMERS];
  639. uint64_t nAccumMax[MICROPROFILE_MAX_TIMERS];
  640. uint64_t nAggregate[MICROPROFILE_MAX_TIMERS];
  641. uint64_t nAggregateMax[MICROPROFILE_MAX_TIMERS];
  642. uint64_t nSum;
  643. uint64_t nSumAccum;
  644. uint64_t nSumAccumMax;
  645. uint64_t nSumAggregate;
  646. uint64_t nSumAggregateMax;
  647. const char* pName;
  648. } MetaCounters[MICROPROFILE_META_MAX];
  649. MicroProfileGraphState Graph[MICROPROFILE_MAX_GRAPHS];
  650. uint32_t nGraphPut;
  651. uint32_t nThreadActive[MICROPROFILE_MAX_THREADS];
  652. MicroProfileThreadLog* Pool[MICROPROFILE_MAX_THREADS];
  653. uint32_t nNumLogs;
  654. uint32_t nMemUsage;
  655. int nFreeListHead;
  656. uint32_t nFrameCurrent;
  657. uint32_t nFrameCurrentIndex;
  658. uint32_t nFramePut;
  659. uint64_t nFramePutIndex;
  660. MicroProfileFrameState Frames[MICROPROFILE_MAX_FRAME_HISTORY];
  661. uint64_t nFlipTicks;
  662. uint64_t nFlipAggregate;
  663. uint64_t nFlipMax;
  664. uint64_t nFlipAggregateDisplay;
  665. uint64_t nFlipMaxDisplay;
  666. MicroProfileThread ContextSwitchThread;
  667. bool bContextSwitchRunning;
  668. bool bContextSwitchStop;
  669. bool bContextSwitchAllThreads;
  670. bool bContextSwitchNoBars;
  671. uint32_t nContextSwitchUsage;
  672. uint32_t nContextSwitchLastPut;
  673. int64_t nContextSwitchHoverTickIn;
  674. int64_t nContextSwitchHoverTickOut;
  675. uint32_t nContextSwitchHoverThread;
  676. uint32_t nContextSwitchHoverThreadBefore;
  677. uint32_t nContextSwitchHoverThreadAfter;
  678. uint8_t nContextSwitchHoverCpu;
  679. uint8_t nContextSwitchHoverCpuNext;
  680. uint32_t nContextSwitchPut;
  681. MicroProfileContextSwitch ContextSwitch[MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE];
  682. MpSocket ListenerSocket;
  683. uint32_t nWebServerPort;
  684. char WebServerBuffer[MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE];
  685. uint32_t WebServerPut;
  686. uint64_t nWebServerDataSent;
  687. MicroProfileGpuTimerState GPU;
  688. };
  689. #define MP_LOG_TICK_MASK 0x0000ffffffffffff
  690. #define MP_LOG_INDEX_MASK 0x3fff000000000000
  691. #define MP_LOG_BEGIN_MASK 0xc000000000000000
  692. #define MP_LOG_GPU_EXTRA 0x3
  693. #define MP_LOG_META 0x2
  694. #define MP_LOG_ENTER 0x1
  695. #define MP_LOG_LEAVE 0x0
  696. inline int MicroProfileLogType(MicroProfileLogEntry Index)
  697. {
  698. return (int)(((MP_LOG_BEGIN_MASK & Index)>>62) & 0x3ULL);
  699. }
  700. inline uint64_t MicroProfileLogTimerIndex(MicroProfileLogEntry Index)
  701. {
  702. return (0x3fff&(Index>>48));
  703. }
  704. inline MicroProfileLogEntry MicroProfileMakeLogIndex(uint64_t nBegin, MicroProfileToken nToken, int64_t nTick)
  705. {
  706. MicroProfileLogEntry Entry = (nBegin<<62) | ((0x3fff&nToken)<<48) | (MP_LOG_TICK_MASK&nTick);
  707. int t = MicroProfileLogType(Entry);
  708. uint64_t nTimerIndex = MicroProfileLogTimerIndex(Entry);
  709. MP_ASSERT((uint64_t)t == nBegin);
  710. MP_ASSERT(nTimerIndex == (nToken&0x3fff));
  711. return Entry;
  712. }
  713. inline int64_t MicroProfileLogTickDifference(MicroProfileLogEntry Start, MicroProfileLogEntry End)
  714. {
  715. uint64_t nStart = Start;
  716. uint64_t nEnd = End;
  717. int64_t nDifference = ((nEnd<<16) - (nStart<<16));
  718. return nDifference >> 16;
  719. }
  720. inline int64_t MicroProfileLogGetTick(MicroProfileLogEntry e)
  721. {
  722. return MP_LOG_TICK_MASK & e;
  723. }
  724. inline int64_t MicroProfileLogSetTick(MicroProfileLogEntry e, int64_t nTick)
  725. {
  726. return (MP_LOG_TICK_MASK & nTick) | (e & ~MP_LOG_TICK_MASK);
  727. }
  728. template<typename T>
  729. T MicroProfileMin(T a, T b)
  730. { return a < b ? a : b; }
  731. template<typename T>
  732. T MicroProfileMax(T a, T b)
  733. { return a > b ? a : b; }
  734. inline int64_t MicroProfileMsToTick(float fMs, int64_t nTicksPerSecond)
  735. {
  736. return (int64_t)(fMs*0.001f*(float)nTicksPerSecond);
  737. }
  738. inline float MicroProfileTickToMsMultiplier(int64_t nTicksPerSecond)
  739. {
  740. return 1000.f / (float)nTicksPerSecond;
  741. }
  742. inline uint16_t MicroProfileGetGroupIndex(MicroProfileToken t)
  743. {
  744. return (uint16_t)MicroProfileGet()->TimerToGroup[MicroProfileGetTimerIndex(t)];
  745. }
  746. #ifdef MICROPROFILE_IMPL
  747. #ifdef _WIN32
  748. #include <windows.h>
  749. #define snprintf _snprintf
  750. #ifdef _MSC_VER
  751. #pragma warning(push)
  752. #pragma warning(disable: 4244)
  753. #endif
  754. int64_t MicroProfileTicksPerSecondCpu()
  755. {
  756. static int64_t nTicksPerSecond = 0;
  757. if(nTicksPerSecond == 0)
  758. {
  759. QueryPerformanceFrequency((LARGE_INTEGER*)&nTicksPerSecond);
  760. }
  761. return nTicksPerSecond;
  762. }
  763. int64_t MicroProfileGetTick()
  764. {
  765. int64_t ticks;
  766. QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
  767. return ticks;
  768. }
  769. #endif
  770. #if defined(MICROPROFILE_WEBSERVER) || defined(MICROPROFILE_CONTEXT_SWITCH_TRACE)
  771. typedef void* (*MicroProfileThreadFunc)(void*);
  772. #ifndef _WIN32
  773. typedef pthread_t MicroProfileThread;
  774. inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func)
  775. {
  776. pthread_attr_t Attr;
  777. int r = pthread_attr_init(&Attr);
  778. MP_ASSERT(r == 0);
  779. pthread_create(pThread, &Attr, Func, 0);
  780. }
  781. inline void MicroProfileThreadJoin(MicroProfileThread* pThread)
  782. {
  783. int r = pthread_join(*pThread, 0);
  784. MP_ASSERT(r == 0);
  785. }
  786. #elif defined(_MSC_VER)
  787. typedef HANDLE MicroProfileThread;
  788. DWORD _stdcall ThreadTrampoline(void* pFunc)
  789. {
  790. MicroProfileThreadFunc F = (MicroProfileThreadFunc)pFunc;
  791. return (DWORD)F(0);
  792. }
  793. inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func)
  794. {
  795. *pThread = CreateThread(0, 0, ThreadTrampoline, Func, 0, 0);
  796. }
  797. inline void MicroProfileThreadJoin(MicroProfileThread* pThread)
  798. {
  799. WaitForSingleObject(*pThread, INFINITE);
  800. CloseHandle(*pThread);
  801. }
  802. #else
  803. #include <thread>
  804. typedef std::thread* MicroProfileThread;
  805. inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func)
  806. {
  807. *pThread = new std::thread(Func, nullptr);
  808. }
  809. inline void MicroProfileThreadJoin(MicroProfileThread* pThread)
  810. {
  811. (*pThread)->join();
  812. delete *pThread;
  813. }
  814. #endif
  815. #endif
  816. #if MICROPROFILE_WEBSERVER
  817. #ifdef _WIN32
  818. #define MP_INVALID_SOCKET(f) (f == INVALID_SOCKET)
  819. #endif
  820. #ifndef _WIN32
  821. #include <sys/socket.h>
  822. #include <netinet/in.h>
  823. #include <fcntl.h>
  824. #define MP_INVALID_SOCKET(f) (f < 0)
  825. #endif
  826. void MicroProfileWebServerStart();
  827. void MicroProfileWebServerStop();
  828. bool MicroProfileWebServerUpdate();
  829. void MicroProfileDumpToFile();
  830. #else
  831. #define MicroProfileWebServerStart() do{}while(0)
  832. #define MicroProfileWebServerStop() do{}while(0)
  833. #define MicroProfileWebServerUpdate() false
  834. #define MicroProfileDumpToFile() do{} while(0)
  835. #endif
  836. #if MICROPROFILE_GPU_TIMERS_D3D11
  837. void MicroProfileGpuFlip();
  838. void MicroProfileGpuShutdown();
  839. #else
  840. #define MicroProfileGpuFlip() do{}while(0)
  841. #define MicroProfileGpuShutdown() do{}while(0)
  842. #endif
  843. #include <stdlib.h>
  844. #include <stdio.h>
  845. #include <math.h>
  846. #include <algorithm>
  847. #ifndef MICROPROFILE_DEBUG
  848. #define MICROPROFILE_DEBUG 0
  849. #endif
  850. #define S g_MicroProfile
  851. MicroProfile g_MicroProfile;
  852. MicroProfileThreadLog* g_MicroProfileGpuLog = 0;
  853. #ifdef MICROPROFILE_IOS
  854. // iOS doesn't support __thread
  855. static pthread_key_t g_MicroProfileThreadLogKey;
  856. static pthread_once_t g_MicroProfileThreadLogKeyOnce = PTHREAD_ONCE_INIT;
  857. static void MicroProfileCreateThreadLogKey()
  858. {
  859. pthread_key_create(&g_MicroProfileThreadLogKey, NULL);
  860. }
  861. #else
  862. MP_THREAD_LOCAL MicroProfileThreadLog* g_MicroProfileThreadLog = 0;
  863. #endif
  864. static std::atomic<bool> g_bUseLock{false}; /// This is used because windows does not support using mutexes under dll init(which is where global initialization is handled)
  865. MICROPROFILE_DEFINE(g_MicroProfileFlip, "MicroProfile", "MicroProfileFlip", 0x3355ee);
  866. MICROPROFILE_DEFINE(g_MicroProfileThreadLoop, "MicroProfile", "ThreadLoop", 0x3355ee);
  867. MICROPROFILE_DEFINE(g_MicroProfileClear, "MicroProfile", "Clear", 0x3355ee);
  868. MICROPROFILE_DEFINE(g_MicroProfileAccumulate, "MicroProfile", "Accumulate", 0x3355ee);
  869. MICROPROFILE_DEFINE(g_MicroProfileContextSwitchSearch,"MicroProfile", "ContextSwitchSearch", 0xDD7300);
  870. inline std::recursive_mutex& MicroProfileMutex()
  871. {
  872. static std::recursive_mutex Mutex;
  873. return Mutex;
  874. }
  875. std::recursive_mutex& MicroProfileGetMutex()
  876. {
  877. return MicroProfileMutex();
  878. }
  879. MICROPROFILE_API MicroProfile* MicroProfileGet()
  880. {
  881. return &g_MicroProfile;
  882. }
  883. MicroProfileThreadLog* MicroProfileCreateThreadLog(const char* pName);
  884. void MicroProfileInit()
  885. {
  886. std::recursive_mutex& mutex = MicroProfileMutex();
  887. bool bUseLock = g_bUseLock;
  888. if(bUseLock)
  889. mutex.lock();
  890. static bool bOnce = true;
  891. if(bOnce)
  892. {
  893. S.nMemUsage += sizeof(S);
  894. bOnce = false;
  895. memset(&S, 0, sizeof(S));
  896. for(int i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  897. {
  898. S.GroupInfo[i].pName[0] = '\0';
  899. }
  900. for(int i = 0; i < MICROPROFILE_MAX_CATEGORIES; ++i)
  901. {
  902. S.CategoryInfo[i].pName[0] = '\0';
  903. S.CategoryInfo[i].nGroupMask = 0;
  904. }
  905. strcpy(&S.CategoryInfo[0].pName[0], "default");
  906. S.nCategoryCount = 1;
  907. for(int i = 0; i < MICROPROFILE_MAX_TIMERS; ++i)
  908. {
  909. S.TimerInfo[i].pName[0] = '\0';
  910. }
  911. S.nGroupCount = 0;
  912. S.nAggregateFlipTick = MP_TICK();
  913. S.nActiveGroup = 0;
  914. S.nActiveBars = 0;
  915. S.nForceGroup = 0;
  916. S.nAllGroupsWanted = 0;
  917. S.nActiveGroupWanted = 0;
  918. S.nAllThreadsWanted = 1;
  919. S.nAggregateFlip = 0;
  920. S.nTotalTimers = 0;
  921. for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i)
  922. {
  923. S.Graph[i].nToken = MICROPROFILE_INVALID_TOKEN;
  924. }
  925. S.nRunning = 1;
  926. S.fReferenceTime = 33.33f;
  927. S.fRcpReferenceTime = 1.f / S.fReferenceTime;
  928. S.nFreeListHead = -1;
  929. int64_t nTick = MP_TICK();
  930. for(int i = 0; i < MICROPROFILE_MAX_FRAME_HISTORY; ++i)
  931. {
  932. S.Frames[i].nFrameStartCpu = nTick;
  933. S.Frames[i].nFrameStartGpu = -1;
  934. }
  935. MicroProfileThreadLog* pGpu = MicroProfileCreateThreadLog("GPU");
  936. g_MicroProfileGpuLog = pGpu;
  937. MP_ASSERT(S.Pool[0] == pGpu);
  938. pGpu->nGpu = 1;
  939. pGpu->nThreadId = 0;
  940. S.nWebServerDataSent = (uint64_t)-1;
  941. }
  942. if(bUseLock)
  943. mutex.unlock();
  944. }
  945. void MicroProfileShutdown()
  946. {
  947. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  948. MicroProfileWebServerStop();
  949. MicroProfileStopContextSwitchTrace();
  950. MicroProfileGpuShutdown();
  951. }
  952. #ifdef MICROPROFILE_IOS
  953. inline MicroProfileThreadLog* MicroProfileGetThreadLog()
  954. {
  955. pthread_once(&g_MicroProfileThreadLogKeyOnce, MicroProfileCreateThreadLogKey);
  956. return (MicroProfileThreadLog*)pthread_getspecific(g_MicroProfileThreadLogKey);
  957. }
  958. inline void MicroProfileSetThreadLog(MicroProfileThreadLog* pLog)
  959. {
  960. pthread_once(&g_MicroProfileThreadLogKeyOnce, MicroProfileCreateThreadLogKey);
  961. pthread_setspecific(g_MicroProfileThreadLogKey, pLog);
  962. }
  963. #else
  964. inline MicroProfileThreadLog* MicroProfileGetThreadLog()
  965. {
  966. return g_MicroProfileThreadLog;
  967. }
  968. inline void MicroProfileSetThreadLog(MicroProfileThreadLog* pLog)
  969. {
  970. g_MicroProfileThreadLog = pLog;
  971. }
  972. #endif
  973. MicroProfileThreadLog* MicroProfileCreateThreadLog(const char* pName)
  974. {
  975. MicroProfileThreadLog* pLog = 0;
  976. if(S.nFreeListHead != -1)
  977. {
  978. pLog = S.Pool[S.nFreeListHead];
  979. MP_ASSERT(pLog->nPut.load() == 0);
  980. MP_ASSERT(pLog->nGet.load() == 0);
  981. S.nFreeListHead = S.Pool[S.nFreeListHead]->nFreeListNext;
  982. pLog->Reset();
  983. }
  984. else
  985. {
  986. pLog = new MicroProfileThreadLog;
  987. S.nMemUsage += sizeof(MicroProfileThreadLog);
  988. S.Pool[S.nNumLogs++] = pLog;
  989. }
  990. int len = (int)strlen(pName);
  991. int maxlen = sizeof(pLog->ThreadName)-1;
  992. len = len < maxlen ? len : maxlen;
  993. memcpy(&pLog->ThreadName[0], pName, len);
  994. pLog->ThreadName[len] = '\0';
  995. pLog->nThreadId = MP_GETCURRENTTHREADID();
  996. pLog->nFreeListNext = -1;
  997. pLog->nActive = 1;
  998. return pLog;
  999. }
  1000. void MicroProfileOnThreadCreate(const char* pThreadName)
  1001. {
  1002. g_bUseLock = true;
  1003. MicroProfileInit();
  1004. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1005. MP_ASSERT(MicroProfileGetThreadLog() == 0);
  1006. MicroProfileThreadLog* pLog = MicroProfileCreateThreadLog(pThreadName ? pThreadName : MicroProfileGetThreadName());
  1007. MP_ASSERT(pLog);
  1008. MicroProfileSetThreadLog(pLog);
  1009. }
  1010. void MicroProfileOnThreadExit()
  1011. {
  1012. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1013. MicroProfileThreadLog* pLog = MicroProfileGetThreadLog();
  1014. if(pLog)
  1015. {
  1016. int32_t nLogIndex = -1;
  1017. for(int i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1018. {
  1019. if(pLog == S.Pool[i])
  1020. {
  1021. nLogIndex = i;
  1022. break;
  1023. }
  1024. }
  1025. MP_ASSERT(nLogIndex < MICROPROFILE_MAX_THREADS && nLogIndex > 0);
  1026. pLog->nFreeListNext = S.nFreeListHead;
  1027. pLog->nActive = 0;
  1028. pLog->nPut.store(0);
  1029. pLog->nGet.store(0);
  1030. S.nFreeListHead = nLogIndex;
  1031. for(int i = 0; i < MICROPROFILE_MAX_FRAME_HISTORY; ++i)
  1032. {
  1033. S.Frames[i].nLogStart[nLogIndex] = 0;
  1034. }
  1035. pLog->nGroupStackPos.fill(0);
  1036. pLog->nGroupTicks.fill(0);
  1037. }
  1038. }
  1039. void MicroProfileInitThreadLog()
  1040. {
  1041. MicroProfileOnThreadCreate(nullptr);
  1042. }
  1043. struct MicroProfileScopeLock
  1044. {
  1045. bool bUseLock;
  1046. std::recursive_mutex& m;
  1047. MicroProfileScopeLock(std::recursive_mutex& m) : bUseLock(g_bUseLock), m(m)
  1048. {
  1049. if(bUseLock)
  1050. m.lock();
  1051. }
  1052. ~MicroProfileScopeLock()
  1053. {
  1054. if(bUseLock)
  1055. m.unlock();
  1056. }
  1057. };
  1058. MicroProfileToken MicroProfileFindToken(const char* pGroup, const char* pName)
  1059. {
  1060. MicroProfileInit();
  1061. MicroProfileScopeLock L(MicroProfileMutex());
  1062. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1063. {
  1064. if(!MP_STRCASECMP(pName, S.TimerInfo[i].pName) && !MP_STRCASECMP(pGroup, S.GroupInfo[S.TimerToGroup[i]].pName))
  1065. {
  1066. return S.TimerInfo[i].nToken;
  1067. }
  1068. }
  1069. return MICROPROFILE_INVALID_TOKEN;
  1070. }
  1071. inline uint16_t MicroProfileGetGroup(const char* pGroup, MicroProfileTokenType Type)
  1072. {
  1073. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  1074. {
  1075. if(!MP_STRCASECMP(pGroup, S.GroupInfo[i].pName))
  1076. {
  1077. return i;
  1078. }
  1079. }
  1080. uint16_t nGroupIndex = 0xffff;
  1081. uint32_t nLen = (uint32_t)strlen(pGroup);
  1082. if(nLen > MICROPROFILE_NAME_MAX_LEN-1)
  1083. nLen = MICROPROFILE_NAME_MAX_LEN-1;
  1084. memcpy(&S.GroupInfo[S.nGroupCount].pName[0], pGroup, nLen);
  1085. S.GroupInfo[S.nGroupCount].pName[nLen] = '\0';
  1086. S.GroupInfo[S.nGroupCount].nNameLen = nLen;
  1087. S.GroupInfo[S.nGroupCount].nNumTimers = 0;
  1088. S.GroupInfo[S.nGroupCount].nGroupIndex = S.nGroupCount;
  1089. S.GroupInfo[S.nGroupCount].Type = Type;
  1090. S.GroupInfo[S.nGroupCount].nMaxTimerNameLen = 0;
  1091. S.GroupInfo[S.nGroupCount].nColor = 0x88888888;
  1092. S.GroupInfo[S.nGroupCount].nCategory = 0;
  1093. S.CategoryInfo[0].nGroupMask |= (1ll << (uint64_t)S.nGroupCount);
  1094. nGroupIndex = S.nGroupCount++;
  1095. S.nGroupMask = (S.nGroupMask<<1)|1;
  1096. MP_ASSERT(nGroupIndex < MICROPROFILE_MAX_GROUPS);
  1097. return nGroupIndex;
  1098. }
  1099. inline void MicroProfileRegisterGroup(const char* pGroup, const char* pCategory, uint32_t nColor)
  1100. {
  1101. int nCategoryIndex = -1;
  1102. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1103. {
  1104. if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName))
  1105. {
  1106. nCategoryIndex = (int)i;
  1107. break;
  1108. }
  1109. }
  1110. if(-1 == nCategoryIndex && S.nCategoryCount < MICROPROFILE_MAX_CATEGORIES)
  1111. {
  1112. MP_ASSERT(S.CategoryInfo[S.nCategoryCount].pName[0] == '\0');
  1113. nCategoryIndex = (int)S.nCategoryCount++;
  1114. uint32_t nLen = (uint32_t)strlen(pCategory);
  1115. if(nLen > MICROPROFILE_NAME_MAX_LEN-1)
  1116. nLen = MICROPROFILE_NAME_MAX_LEN-1;
  1117. memcpy(&S.CategoryInfo[nCategoryIndex].pName[0], pCategory, nLen);
  1118. S.CategoryInfo[nCategoryIndex].pName[nLen] = '\0';
  1119. }
  1120. uint16_t nGroup = MicroProfileGetGroup(pGroup, 0 != MP_STRCASECMP(pGroup, "gpu")?MicroProfileTokenTypeCpu : MicroProfileTokenTypeGpu);
  1121. S.GroupInfo[nGroup].nColor = nColor;
  1122. if(nCategoryIndex >= 0)
  1123. {
  1124. uint64_t nBit = 1ll << nGroup;
  1125. uint32_t nOldCategory = S.GroupInfo[nGroup].nCategory;
  1126. S.CategoryInfo[nOldCategory].nGroupMask &= ~nBit;
  1127. S.CategoryInfo[nCategoryIndex].nGroupMask |= nBit;
  1128. S.GroupInfo[nGroup].nCategory = nCategoryIndex;
  1129. }
  1130. }
  1131. MicroProfileToken MicroProfileGetToken(const char* pGroup, const char* pName, uint32_t nColor, MicroProfileTokenType Type)
  1132. {
  1133. MicroProfileInit();
  1134. MicroProfileScopeLock L(MicroProfileMutex());
  1135. MicroProfileToken ret = MicroProfileFindToken(pGroup, pName);
  1136. if(ret != MICROPROFILE_INVALID_TOKEN)
  1137. return ret;
  1138. uint16_t nGroupIndex = MicroProfileGetGroup(pGroup, Type);
  1139. uint16_t nTimerIndex = (uint16_t)(S.nTotalTimers++);
  1140. uint64_t nGroupMask = 1ll << nGroupIndex;
  1141. MicroProfileToken nToken = MicroProfileMakeToken(nGroupMask, nTimerIndex);
  1142. S.GroupInfo[nGroupIndex].nNumTimers++;
  1143. S.GroupInfo[nGroupIndex].nMaxTimerNameLen = MicroProfileMax(S.GroupInfo[nGroupIndex].nMaxTimerNameLen, (uint32_t)strlen(pName));
  1144. MP_ASSERT(S.GroupInfo[nGroupIndex].Type == Type); //dont mix cpu & gpu timers in the same group
  1145. S.nMaxGroupSize = MicroProfileMax(S.nMaxGroupSize, S.GroupInfo[nGroupIndex].nNumTimers);
  1146. S.TimerInfo[nTimerIndex].nToken = nToken;
  1147. uint32_t nLen = (uint32_t)strlen(pName);
  1148. if(nLen > MICROPROFILE_NAME_MAX_LEN-1)
  1149. nLen = MICROPROFILE_NAME_MAX_LEN-1;
  1150. memcpy(&S.TimerInfo[nTimerIndex].pName, pName, nLen);
  1151. S.TimerInfo[nTimerIndex].pName[nLen] = '\0';
  1152. S.TimerInfo[nTimerIndex].nNameLen = nLen;
  1153. S.TimerInfo[nTimerIndex].nColor = nColor&0xffffff;
  1154. S.TimerInfo[nTimerIndex].nGroupIndex = nGroupIndex;
  1155. S.TimerInfo[nTimerIndex].nTimerIndex = nTimerIndex;
  1156. S.TimerToGroup[nTimerIndex] = nGroupIndex;
  1157. return nToken;
  1158. }
  1159. MicroProfileToken MicroProfileGetMetaToken(const char* pName)
  1160. {
  1161. MicroProfileInit();
  1162. MicroProfileScopeLock L(MicroProfileMutex());
  1163. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1164. {
  1165. if(!S.MetaCounters[i].pName)
  1166. {
  1167. S.MetaCounters[i].pName = pName;
  1168. return i;
  1169. }
  1170. else if(!MP_STRCASECMP(pName, S.MetaCounters[i].pName))
  1171. {
  1172. return i;
  1173. }
  1174. }
  1175. MP_ASSERT(0);//out of slots, increase MICROPROFILE_META_MAX
  1176. return (MicroProfileToken)-1;
  1177. }
  1178. inline void MicroProfileLogPut(MicroProfileToken nToken_, uint64_t nTick, uint64_t nBegin, MicroProfileThreadLog* pLog)
  1179. {
  1180. MP_ASSERT(pLog != 0); //this assert is hit if MicroProfileOnCreateThread is not called
  1181. MP_ASSERT(pLog->nActive);
  1182. uint32_t nPos = pLog->nPut.load(std::memory_order_relaxed);
  1183. uint32_t nNextPos = (nPos+1) % MICROPROFILE_BUFFER_SIZE;
  1184. if(nNextPos == pLog->nGet.load(std::memory_order_relaxed))
  1185. {
  1186. S.nOverflow = 100;
  1187. }
  1188. else
  1189. {
  1190. pLog->Log[nPos] = MicroProfileMakeLogIndex(nBegin, nToken_, nTick);
  1191. pLog->nPut.store(nNextPos, std::memory_order_release);
  1192. }
  1193. }
  1194. uint64_t MicroProfileEnter(MicroProfileToken nToken_)
  1195. {
  1196. if(MicroProfileGetGroupMask(nToken_) & S.nActiveGroup)
  1197. {
  1198. if(!MicroProfileGetThreadLog())
  1199. {
  1200. MicroProfileInitThreadLog();
  1201. }
  1202. uint64_t nTick = MP_TICK();
  1203. MicroProfileLogPut(nToken_, nTick, MP_LOG_ENTER, MicroProfileGetThreadLog());
  1204. return nTick;
  1205. }
  1206. return MICROPROFILE_INVALID_TICK;
  1207. }
  1208. void MicroProfileMetaUpdate(MicroProfileToken nToken, int nCount, MicroProfileTokenType eTokenType)
  1209. {
  1210. if((MP_DRAW_META_FIRST<<nToken) & S.nActiveBars)
  1211. {
  1212. MicroProfileThreadLog* pLog = MicroProfileTokenTypeCpu == eTokenType ? MicroProfileGetThreadLog() : g_MicroProfileGpuLog;
  1213. if(pLog)
  1214. {
  1215. MP_ASSERT(nToken < MICROPROFILE_META_MAX);
  1216. MicroProfileLogPut(nToken, nCount, MP_LOG_META, pLog);
  1217. }
  1218. }
  1219. }
  1220. void MicroProfileLeave(MicroProfileToken nToken_, uint64_t nTickStart)
  1221. {
  1222. if(MICROPROFILE_INVALID_TICK != nTickStart)
  1223. {
  1224. if(!MicroProfileGetThreadLog())
  1225. {
  1226. MicroProfileInitThreadLog();
  1227. }
  1228. uint64_t nTick = MP_TICK();
  1229. MicroProfileThreadLog* pLog = MicroProfileGetThreadLog();
  1230. MicroProfileLogPut(nToken_, nTick, MP_LOG_LEAVE, pLog);
  1231. }
  1232. }
  1233. uint64_t MicroProfileGpuEnter(MicroProfileToken nToken_)
  1234. {
  1235. if(MicroProfileGetGroupMask(nToken_) & S.nActiveGroup)
  1236. {
  1237. uint64_t nTimer = MicroProfileGpuInsertTimeStamp();
  1238. MicroProfileLogPut(nToken_, nTimer, MP_LOG_ENTER, g_MicroProfileGpuLog);
  1239. MicroProfileLogPut(nToken_, MP_TICK(), MP_LOG_GPU_EXTRA, g_MicroProfileGpuLog);
  1240. return 1;
  1241. }
  1242. return 0;
  1243. }
  1244. void MicroProfileGpuLeave(MicroProfileToken nToken_, uint64_t nTickStart)
  1245. {
  1246. if(nTickStart)
  1247. {
  1248. uint64_t nTimer = MicroProfileGpuInsertTimeStamp();
  1249. MicroProfileLogPut(nToken_, nTimer, MP_LOG_LEAVE, g_MicroProfileGpuLog);
  1250. MicroProfileLogPut(nToken_, MP_TICK(), MP_LOG_GPU_EXTRA, g_MicroProfileGpuLog);
  1251. }
  1252. }
  1253. inline void MicroProfileContextSwitchPut(MicroProfileContextSwitch* pContextSwitch)
  1254. {
  1255. if(S.nRunning || pContextSwitch->nTicks <= S.nPauseTicks)
  1256. {
  1257. uint32_t nPut = S.nContextSwitchPut;
  1258. S.ContextSwitch[nPut] = *pContextSwitch;
  1259. S.nContextSwitchPut = (S.nContextSwitchPut+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1260. }
  1261. }
  1262. void MicroProfileGetRange(uint32_t nPut, uint32_t nGet, uint32_t nRange[2][2])
  1263. {
  1264. if(nPut > nGet)
  1265. {
  1266. nRange[0][0] = nGet;
  1267. nRange[0][1] = nPut;
  1268. nRange[1][0] = nRange[1][1] = 0;
  1269. }
  1270. else if(nPut != nGet)
  1271. {
  1272. MP_ASSERT(nGet != MICROPROFILE_BUFFER_SIZE);
  1273. uint32_t nCountEnd = MICROPROFILE_BUFFER_SIZE - nGet;
  1274. nRange[0][0] = nGet;
  1275. nRange[0][1] = nGet + nCountEnd;
  1276. nRange[1][0] = 0;
  1277. nRange[1][1] = nPut;
  1278. }
  1279. }
  1280. void MicroProfileFlip()
  1281. {
  1282. #if 0
  1283. //verify LogEntry wraps correctly
  1284. MicroProfileLogEntry c = MP_LOG_TICK_MASK-5000;
  1285. for(int i = 0; i < 10000; ++i, c += 1)
  1286. {
  1287. MicroProfileLogEntry l2 = (c+2500) & MP_LOG_TICK_MASK;
  1288. MP_ASSERT(2500 == MicroProfileLogTickDifference(c, l2));
  1289. }
  1290. #endif
  1291. MICROPROFILE_SCOPE(g_MicroProfileFlip);
  1292. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1293. MicroProfileGpuFlip();
  1294. if(S.nToggleRunning)
  1295. {
  1296. S.nRunning = !S.nRunning;
  1297. if(!S.nRunning)
  1298. S.nPauseTicks = MP_TICK();
  1299. S.nToggleRunning = 0;
  1300. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1301. {
  1302. MicroProfileThreadLog* pLog = S.Pool[i];
  1303. if(pLog)
  1304. {
  1305. pLog->nStackPos = 0;
  1306. }
  1307. }
  1308. }
  1309. uint32_t nAggregateClear = S.nAggregateClear || S.nAutoClearFrames, nAggregateFlip = 0;
  1310. if(S.nDumpFileNextFrame)
  1311. {
  1312. MicroProfileDumpToFile();
  1313. S.nDumpFileNextFrame = 0;
  1314. S.nAutoClearFrames = MICROPROFILE_GPU_FRAME_DELAY + 3; //hide spike from dumping webpage
  1315. }
  1316. if(S.nWebServerDataSent == (uint64_t)-1)
  1317. {
  1318. MicroProfileWebServerStart();
  1319. S.nWebServerDataSent = 0;
  1320. }
  1321. if(MicroProfileWebServerUpdate())
  1322. {
  1323. S.nAutoClearFrames = MICROPROFILE_GPU_FRAME_DELAY + 3; //hide spike from dumping webpage
  1324. }
  1325. if(S.nAutoClearFrames)
  1326. {
  1327. nAggregateClear = 1;
  1328. nAggregateFlip = 1;
  1329. S.nAutoClearFrames -= 1;
  1330. }
  1331. if(S.nRunning || S.nForceEnable)
  1332. {
  1333. S.nFramePutIndex++;
  1334. S.nFramePut = (S.nFramePut+1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1335. MP_ASSERT((S.nFramePutIndex % MICROPROFILE_MAX_FRAME_HISTORY) == S.nFramePut);
  1336. S.nFrameCurrent = (S.nFramePut + MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1337. S.nFrameCurrentIndex++;
  1338. uint32_t nFrameNext = (S.nFrameCurrent+1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1339. uint32_t nContextSwitchPut = S.nContextSwitchPut;
  1340. if(S.nContextSwitchLastPut < nContextSwitchPut)
  1341. {
  1342. S.nContextSwitchUsage = (nContextSwitchPut - S.nContextSwitchLastPut);
  1343. }
  1344. else
  1345. {
  1346. S.nContextSwitchUsage = MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - S.nContextSwitchLastPut + nContextSwitchPut;
  1347. }
  1348. S.nContextSwitchLastPut = nContextSwitchPut;
  1349. MicroProfileFrameState* pFramePut = &S.Frames[S.nFramePut];
  1350. MicroProfileFrameState* pFrameCurrent = &S.Frames[S.nFrameCurrent];
  1351. MicroProfileFrameState* pFrameNext = &S.Frames[nFrameNext];
  1352. pFramePut->nFrameStartCpu = MP_TICK();
  1353. pFramePut->nFrameStartGpu = (uint32_t)MicroProfileGpuInsertTimeStamp();
  1354. if(pFrameNext->nFrameStartGpu != -1)
  1355. pFrameNext->nFrameStartGpu = MicroProfileGpuGetTimeStamp((uint32_t)pFrameNext->nFrameStartGpu);
  1356. if(pFrameCurrent->nFrameStartGpu == -1)
  1357. pFrameCurrent->nFrameStartGpu = pFrameNext->nFrameStartGpu + 1;
  1358. uint64_t nFrameStartCpu = pFrameCurrent->nFrameStartCpu;
  1359. uint64_t nFrameEndCpu = pFrameNext->nFrameStartCpu;
  1360. {
  1361. uint64_t nTick = nFrameEndCpu - nFrameStartCpu;
  1362. S.nFlipTicks = nTick;
  1363. S.nFlipAggregate += nTick;
  1364. S.nFlipMax = MicroProfileMax(S.nFlipMax, nTick);
  1365. }
  1366. uint8_t* pTimerToGroup = &S.TimerToGroup[0];
  1367. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1368. {
  1369. MicroProfileThreadLog* pLog = S.Pool[i];
  1370. if(!pLog)
  1371. {
  1372. pFramePut->nLogStart[i] = 0;
  1373. }
  1374. else
  1375. {
  1376. uint32_t nPut = pLog->nPut.load(std::memory_order_acquire);
  1377. pFramePut->nLogStart[i] = nPut;
  1378. MP_ASSERT(nPut< MICROPROFILE_BUFFER_SIZE);
  1379. //need to keep last frame around to close timers. timers more than 1 frame old is ditched.
  1380. pLog->nGet.store(nPut, std::memory_order_relaxed);
  1381. }
  1382. }
  1383. if(S.nRunning)
  1384. {
  1385. uint64_t* pFrameGroup = &S.FrameGroup[0];
  1386. {
  1387. MICROPROFILE_SCOPE(g_MicroProfileClear);
  1388. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1389. {
  1390. S.Frame[i].nTicks = 0;
  1391. S.Frame[i].nCount = 0;
  1392. S.FrameExclusive[i] = 0;
  1393. }
  1394. for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  1395. {
  1396. pFrameGroup[i] = 0;
  1397. }
  1398. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1399. {
  1400. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1401. {
  1402. auto& Meta = S.MetaCounters[j];
  1403. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1404. {
  1405. Meta.nCounters[i] = 0;
  1406. }
  1407. }
  1408. }
  1409. }
  1410. {
  1411. MICROPROFILE_SCOPE(g_MicroProfileThreadLoop);
  1412. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1413. {
  1414. MicroProfileThreadLog* pLog = S.Pool[i];
  1415. if(!pLog)
  1416. continue;
  1417. uint8_t* pGroupStackPos = &pLog->nGroupStackPos[0];
  1418. int64_t nGroupTicks[MICROPROFILE_MAX_GROUPS] = {0};
  1419. uint32_t nPut = pFrameNext->nLogStart[i];
  1420. uint32_t nGet = pFrameCurrent->nLogStart[i];
  1421. uint32_t nRange[2][2] = { {0, 0}, {0, 0}, };
  1422. MicroProfileGetRange(nPut, nGet, nRange);
  1423. //fetch gpu results.
  1424. if(pLog->nGpu)
  1425. {
  1426. for(uint32_t j = 0; j < 2; ++j)
  1427. {
  1428. uint32_t nStart = nRange[j][0];
  1429. uint32_t nEnd = nRange[j][1];
  1430. for(uint32_t k = nStart; k < nEnd; ++k)
  1431. {
  1432. MicroProfileLogEntry L = pLog->Log[k];
  1433. if(MicroProfileLogType(L) < MP_LOG_META)
  1434. {
  1435. pLog->Log[k] = MicroProfileLogSetTick(L, MicroProfileGpuGetTimeStamp((uint32_t)MicroProfileLogGetTick(L)));
  1436. }
  1437. }
  1438. }
  1439. }
  1440. uint32_t* pStack = &pLog->nStack[0];
  1441. int64_t* pChildTickStack = &pLog->nChildTickStack[0];
  1442. uint32_t nStackPos = pLog->nStackPos;
  1443. for(uint32_t j = 0; j < 2; ++j)
  1444. {
  1445. uint32_t nStart = nRange[j][0];
  1446. uint32_t nEnd = nRange[j][1];
  1447. for(uint32_t k = nStart; k < nEnd; ++k)
  1448. {
  1449. MicroProfileLogEntry LE = pLog->Log[k];
  1450. int nType = MicroProfileLogType(LE);
  1451. if(MP_LOG_ENTER == nType)
  1452. {
  1453. int nTimer = MicroProfileLogTimerIndex(LE);
  1454. uint8_t nGroup = pTimerToGroup[nTimer];
  1455. MP_ASSERT(nStackPos < MICROPROFILE_STACK_MAX);
  1456. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1457. pGroupStackPos[nGroup]++;
  1458. pStack[nStackPos++] = k;
  1459. pChildTickStack[nStackPos] = 0;
  1460. }
  1461. else if(MP_LOG_META == nType)
  1462. {
  1463. if(nStackPos)
  1464. {
  1465. int64_t nMetaIndex = MicroProfileLogTimerIndex(LE);
  1466. int64_t nMetaCount = MicroProfileLogGetTick(LE);
  1467. MP_ASSERT(nMetaIndex < MICROPROFILE_META_MAX);
  1468. int64_t nCounter = MicroProfileLogTimerIndex(pLog->Log[pStack[nStackPos-1]]);
  1469. S.MetaCounters[nMetaIndex].nCounters[nCounter] += nMetaCount;
  1470. }
  1471. }
  1472. else if(MP_LOG_LEAVE == nType)
  1473. {
  1474. int nTimer = MicroProfileLogTimerIndex(LE);
  1475. uint8_t nGroup = pTimerToGroup[nTimer];
  1476. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1477. if(nStackPos)
  1478. {
  1479. int64_t nTickStart = pLog->Log[pStack[nStackPos-1]];
  1480. int64_t nTicks = MicroProfileLogTickDifference(nTickStart, LE);
  1481. int64_t nChildTicks = pChildTickStack[nStackPos];
  1482. nStackPos--;
  1483. pChildTickStack[nStackPos] += nTicks;
  1484. uint32_t nTimerIndex = MicroProfileLogTimerIndex(LE);
  1485. S.Frame[nTimerIndex].nTicks += nTicks;
  1486. S.FrameExclusive[nTimerIndex] += (nTicks-nChildTicks);
  1487. S.Frame[nTimerIndex].nCount += 1;
  1488. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1489. uint8_t nGroupStackPos = pGroupStackPos[nGroup];
  1490. if(nGroupStackPos)
  1491. {
  1492. nGroupStackPos--;
  1493. if(0 == nGroupStackPos)
  1494. {
  1495. nGroupTicks[nGroup] += nTicks;
  1496. }
  1497. pGroupStackPos[nGroup] = nGroupStackPos;
  1498. }
  1499. }
  1500. }
  1501. }
  1502. }
  1503. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1504. {
  1505. pLog->nGroupTicks[j] += nGroupTicks[j];
  1506. pFrameGroup[j] += nGroupTicks[j];
  1507. }
  1508. pLog->nStackPos = nStackPos;
  1509. }
  1510. }
  1511. {
  1512. MICROPROFILE_SCOPE(g_MicroProfileAccumulate);
  1513. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1514. {
  1515. S.AccumTimers[i].nTicks += S.Frame[i].nTicks;
  1516. S.AccumTimers[i].nCount += S.Frame[i].nCount;
  1517. S.AccumMaxTimers[i] = MicroProfileMax(S.AccumMaxTimers[i], S.Frame[i].nTicks);
  1518. S.AccumTimersExclusive[i] += S.FrameExclusive[i];
  1519. S.AccumMaxTimersExclusive[i] = MicroProfileMax(S.AccumMaxTimersExclusive[i], S.FrameExclusive[i]);
  1520. }
  1521. for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  1522. {
  1523. S.AccumGroup[i] += pFrameGroup[i];
  1524. S.AccumGroupMax[i] = MicroProfileMax(S.AccumGroupMax[i], pFrameGroup[i]);
  1525. }
  1526. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1527. {
  1528. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1529. {
  1530. auto& Meta = S.MetaCounters[j];
  1531. uint64_t nSum = 0;;
  1532. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1533. {
  1534. uint64_t nCounter = Meta.nCounters[i];
  1535. Meta.nAccumMax[i] = MicroProfileMax(Meta.nAccumMax[i], nCounter);
  1536. Meta.nAccum[i] += nCounter;
  1537. nSum += nCounter;
  1538. }
  1539. Meta.nSumAccum += nSum;
  1540. Meta.nSumAccumMax = MicroProfileMax(Meta.nSumAccumMax, nSum);
  1541. }
  1542. }
  1543. }
  1544. for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i)
  1545. {
  1546. if(S.Graph[i].nToken != MICROPROFILE_INVALID_TOKEN)
  1547. {
  1548. MicroProfileToken nToken = S.Graph[i].nToken;
  1549. S.Graph[i].nHistory[S.nGraphPut] = S.Frame[MicroProfileGetTimerIndex(nToken)].nTicks;
  1550. }
  1551. }
  1552. S.nGraphPut = (S.nGraphPut+1) % MICROPROFILE_GRAPH_HISTORY;
  1553. }
  1554. if(S.nRunning && S.nAggregateFlip <= ++S.nAggregateFlipCount)
  1555. {
  1556. nAggregateFlip = 1;
  1557. if(S.nAggregateFlip) // if 0 accumulate indefinitely
  1558. {
  1559. nAggregateClear = 1;
  1560. }
  1561. }
  1562. }
  1563. if(nAggregateFlip)
  1564. {
  1565. memcpy(&S.Aggregate[0], &S.AccumTimers[0], sizeof(S.Aggregate[0]) * S.nTotalTimers);
  1566. memcpy(&S.AggregateMax[0], &S.AccumMaxTimers[0], sizeof(S.AggregateMax[0]) * S.nTotalTimers);
  1567. memcpy(&S.AggregateExclusive[0], &S.AccumTimersExclusive[0], sizeof(S.AggregateExclusive[0]) * S.nTotalTimers);
  1568. memcpy(&S.AggregateMaxExclusive[0], &S.AccumMaxTimersExclusive[0], sizeof(S.AggregateMaxExclusive[0]) * S.nTotalTimers);
  1569. memcpy(&S.AggregateGroup[0], &S.AccumGroup[0], sizeof(S.AggregateGroup));
  1570. memcpy(&S.AggregateGroupMax[0], &S.AccumGroupMax[0], sizeof(S.AggregateGroup));
  1571. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1572. {
  1573. MicroProfileThreadLog* pLog = S.Pool[i];
  1574. if(!pLog)
  1575. continue;
  1576. memcpy(&pLog->nAggregateGroupTicks[0], &pLog->nGroupTicks[0], sizeof(pLog->nAggregateGroupTicks));
  1577. if(nAggregateClear)
  1578. {
  1579. memset(&pLog->nGroupTicks[0], 0, sizeof(pLog->nGroupTicks));
  1580. }
  1581. }
  1582. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1583. {
  1584. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1585. {
  1586. auto& Meta = S.MetaCounters[j];
  1587. memcpy(&Meta.nAggregateMax[0], &Meta.nAccumMax[0], sizeof(Meta.nAggregateMax[0]) * S.nTotalTimers);
  1588. memcpy(&Meta.nAggregate[0], &Meta.nAccum[0], sizeof(Meta.nAggregate[0]) * S.nTotalTimers);
  1589. Meta.nSumAggregate = Meta.nSumAccum;
  1590. Meta.nSumAggregateMax = Meta.nSumAccumMax;
  1591. if(nAggregateClear)
  1592. {
  1593. memset(&Meta.nAccumMax[0], 0, sizeof(Meta.nAccumMax[0]) * S.nTotalTimers);
  1594. memset(&Meta.nAccum[0], 0, sizeof(Meta.nAccum[0]) * S.nTotalTimers);
  1595. Meta.nSumAccum = 0;
  1596. Meta.nSumAccumMax = 0;
  1597. }
  1598. }
  1599. }
  1600. S.nAggregateFrames = S.nAggregateFlipCount;
  1601. S.nFlipAggregateDisplay = S.nFlipAggregate;
  1602. S.nFlipMaxDisplay = S.nFlipMax;
  1603. if(nAggregateClear)
  1604. {
  1605. memset(&S.AccumTimers[0], 0, sizeof(S.Aggregate[0]) * S.nTotalTimers);
  1606. memset(&S.AccumMaxTimers[0], 0, sizeof(S.AccumMaxTimers[0]) * S.nTotalTimers);
  1607. memset(&S.AccumTimersExclusive[0], 0, sizeof(S.AggregateExclusive[0]) * S.nTotalTimers);
  1608. memset(&S.AccumMaxTimersExclusive[0], 0, sizeof(S.AccumMaxTimersExclusive[0]) * S.nTotalTimers);
  1609. memset(&S.AccumGroup[0], 0, sizeof(S.AggregateGroup));
  1610. memset(&S.AccumGroupMax[0], 0, sizeof(S.AggregateGroup));
  1611. S.nAggregateFlipCount = 0;
  1612. S.nFlipAggregate = 0;
  1613. S.nFlipMax = 0;
  1614. S.nAggregateFlipTick = MP_TICK();
  1615. }
  1616. }
  1617. S.nAggregateClear = 0;
  1618. uint64_t nNewActiveGroup = 0;
  1619. if(S.nForceEnable || (S.nDisplay && S.nRunning))
  1620. nNewActiveGroup = S.nAllGroupsWanted ? S.nGroupMask : S.nActiveGroupWanted;
  1621. nNewActiveGroup |= S.nForceGroup;
  1622. nNewActiveGroup |= S.nForceGroupUI;
  1623. if(S.nActiveGroup != nNewActiveGroup)
  1624. S.nActiveGroup = nNewActiveGroup;
  1625. uint32_t nNewActiveBars = 0;
  1626. if(S.nDisplay && S.nRunning)
  1627. nNewActiveBars = S.nBars;
  1628. if(S.nForceMetaCounters)
  1629. {
  1630. for(int i = 0; i < MICROPROFILE_META_MAX; ++i)
  1631. {
  1632. if(S.MetaCounters[i].pName)
  1633. {
  1634. nNewActiveBars |= (MP_DRAW_META_FIRST<<i);
  1635. }
  1636. }
  1637. }
  1638. if(nNewActiveBars != S.nActiveBars)
  1639. S.nActiveBars = nNewActiveBars;
  1640. }
  1641. void MicroProfileSetForceEnable(bool bEnable)
  1642. {
  1643. S.nForceEnable = bEnable ? 1 : 0;
  1644. }
  1645. bool MicroProfileGetForceEnable()
  1646. {
  1647. return S.nForceEnable != 0;
  1648. }
  1649. void MicroProfileSetEnableAllGroups(bool bEnableAllGroups)
  1650. {
  1651. S.nAllGroupsWanted = bEnableAllGroups ? 1 : 0;
  1652. }
  1653. inline void MicroProfileEnableCategory(const char* pCategory, bool bEnabled)
  1654. {
  1655. int nCategoryIndex = -1;
  1656. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1657. {
  1658. if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName))
  1659. {
  1660. nCategoryIndex = (int)i;
  1661. break;
  1662. }
  1663. }
  1664. if(nCategoryIndex >= 0)
  1665. {
  1666. if(bEnabled)
  1667. {
  1668. S.nActiveGroupWanted |= S.CategoryInfo[nCategoryIndex].nGroupMask;
  1669. }
  1670. else
  1671. {
  1672. S.nActiveGroupWanted &= ~S.CategoryInfo[nCategoryIndex].nGroupMask;
  1673. }
  1674. }
  1675. }
  1676. void MicroProfileEnableCategory(const char* pCategory)
  1677. {
  1678. MicroProfileEnableCategory(pCategory, true);
  1679. }
  1680. void MicroProfileDisableCategory(const char* pCategory)
  1681. {
  1682. MicroProfileEnableCategory(pCategory, false);
  1683. }
  1684. bool MicroProfileGetEnableAllGroups()
  1685. {
  1686. return 0 != S.nAllGroupsWanted;
  1687. }
  1688. void MicroProfileSetForceMetaCounters(bool bForce)
  1689. {
  1690. S.nForceMetaCounters = bForce ? 1 : 0;
  1691. }
  1692. bool MicroProfileGetForceMetaCounters()
  1693. {
  1694. return 0 != S.nForceMetaCounters;
  1695. }
  1696. void MicroProfileEnableMetaCounter(const char* pMeta)
  1697. {
  1698. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1699. {
  1700. if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta))
  1701. {
  1702. S.nBars |= (MP_DRAW_META_FIRST<<i);
  1703. return;
  1704. }
  1705. }
  1706. }
  1707. void MicroProfileDisableMetaCounter(const char* pMeta)
  1708. {
  1709. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1710. {
  1711. if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta))
  1712. {
  1713. S.nBars &= ~(MP_DRAW_META_FIRST<<i);
  1714. return;
  1715. }
  1716. }
  1717. }
  1718. void MicroProfileSetAggregateFrames(int nFrames)
  1719. {
  1720. S.nAggregateFlip = (uint32_t)nFrames;
  1721. if(0 == nFrames)
  1722. {
  1723. S.nAggregateClear = 1;
  1724. }
  1725. }
  1726. int MicroProfileGetAggregateFrames()
  1727. {
  1728. return S.nAggregateFlip;
  1729. }
  1730. int MicroProfileGetCurrentAggregateFrames()
  1731. {
  1732. return int(S.nAggregateFlip ? S.nAggregateFlip : S.nAggregateFlipCount);
  1733. }
  1734. void MicroProfileForceEnableGroup(const char* pGroup, MicroProfileTokenType Type)
  1735. {
  1736. MicroProfileInit();
  1737. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1738. uint16_t nGroup = MicroProfileGetGroup(pGroup, Type);
  1739. S.nForceGroup |= (1ll << nGroup);
  1740. }
  1741. void MicroProfileForceDisableGroup(const char* pGroup, MicroProfileTokenType Type)
  1742. {
  1743. MicroProfileInit();
  1744. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1745. uint16_t nGroup = MicroProfileGetGroup(pGroup, Type);
  1746. S.nForceGroup &= ~(1ll << nGroup);
  1747. }
  1748. inline void MicroProfileCalcAllTimers(float* pTimers, float* pAverage, float* pMax, float* pCallAverage, float* pExclusive, float* pAverageExclusive, float* pMaxExclusive, float* pTotal, uint32_t nSize)
  1749. {
  1750. for(uint32_t i = 0; i < S.nTotalTimers && i < nSize; ++i)
  1751. {
  1752. const uint32_t nGroupId = S.TimerInfo[i].nGroupIndex;
  1753. const float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupId].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu());
  1754. uint32_t nTimer = i;
  1755. uint32_t nIdx = i * 2;
  1756. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  1757. uint32_t nAggregateCount = S.Aggregate[nTimer].nCount ? S.Aggregate[nTimer].nCount : 1;
  1758. float fToPrc = S.fRcpReferenceTime;
  1759. float fMs = fToMs * (S.Frame[nTimer].nTicks);
  1760. float fPrc = MicroProfileMin(fMs * fToPrc, 1.f);
  1761. float fAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateFrames);
  1762. float fAveragePrc = MicroProfileMin(fAverageMs * fToPrc, 1.f);
  1763. float fMaxMs = fToMs * (S.AggregateMax[nTimer]);
  1764. float fMaxPrc = MicroProfileMin(fMaxMs * fToPrc, 1.f);
  1765. float fCallAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateCount);
  1766. float fCallAveragePrc = MicroProfileMin(fCallAverageMs * fToPrc, 1.f);
  1767. float fMsExclusive = fToMs * (S.FrameExclusive[nTimer]);
  1768. float fPrcExclusive = MicroProfileMin(fMsExclusive * fToPrc, 1.f);
  1769. float fAverageMsExclusive = fToMs * (S.AggregateExclusive[nTimer] / nAggregateFrames);
  1770. float fAveragePrcExclusive = MicroProfileMin(fAverageMsExclusive * fToPrc, 1.f);
  1771. float fMaxMsExclusive = fToMs * (S.AggregateMaxExclusive[nTimer]);
  1772. float fMaxPrcExclusive = MicroProfileMin(fMaxMsExclusive * fToPrc, 1.f);
  1773. float fTotalMs = fToMs * S.Aggregate[nTimer].nTicks;
  1774. pTimers[nIdx] = fMs;
  1775. pTimers[nIdx+1] = fPrc;
  1776. pAverage[nIdx] = fAverageMs;
  1777. pAverage[nIdx+1] = fAveragePrc;
  1778. pMax[nIdx] = fMaxMs;
  1779. pMax[nIdx+1] = fMaxPrc;
  1780. pCallAverage[nIdx] = fCallAverageMs;
  1781. pCallAverage[nIdx+1] = fCallAveragePrc;
  1782. pExclusive[nIdx] = fMsExclusive;
  1783. pExclusive[nIdx+1] = fPrcExclusive;
  1784. pAverageExclusive[nIdx] = fAverageMsExclusive;
  1785. pAverageExclusive[nIdx+1] = fAveragePrcExclusive;
  1786. pMaxExclusive[nIdx] = fMaxMsExclusive;
  1787. pMaxExclusive[nIdx+1] = fMaxPrcExclusive;
  1788. pTotal[nIdx] = fTotalMs;
  1789. pTotal[nIdx+1] = 0.f;
  1790. }
  1791. }
  1792. void MicroProfileTogglePause()
  1793. {
  1794. S.nToggleRunning = 1;
  1795. }
  1796. float MicroProfileGetTime(const char* pGroup, const char* pName)
  1797. {
  1798. MicroProfileToken nToken = MicroProfileFindToken(pGroup, pName);
  1799. if(nToken == MICROPROFILE_INVALID_TOKEN)
  1800. {
  1801. return 0.f;
  1802. }
  1803. uint32_t nTimerIndex = MicroProfileGetTimerIndex(nToken);
  1804. uint32_t nGroupIndex = MicroProfileGetGroupIndex(nToken);
  1805. float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupIndex].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu());
  1806. return S.Frame[nTimerIndex].nTicks * fToMs;
  1807. }
  1808. void MicroProfileContextSwitchSearch(uint32_t* pContextSwitchStart, uint32_t* pContextSwitchEnd, uint64_t nBaseTicksCpu, uint64_t nBaseTicksEndCpu)
  1809. {
  1810. MICROPROFILE_SCOPE(g_MicroProfileContextSwitchSearch);
  1811. uint32_t nContextSwitchPut = S.nContextSwitchPut;
  1812. uint64_t nContextSwitchStart, nContextSwitchEnd;
  1813. nContextSwitchStart = nContextSwitchEnd = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - 1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1814. int64_t nSearchEnd = nBaseTicksEndCpu + MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu());
  1815. int64_t nSearchBegin = nBaseTicksCpu - MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu());
  1816. for(uint32_t i = 0; i < MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; ++i)
  1817. {
  1818. uint32_t nIndex = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - (i+1)) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1819. MicroProfileContextSwitch& CS = S.ContextSwitch[nIndex];
  1820. if(CS.nTicks > nSearchEnd)
  1821. {
  1822. nContextSwitchEnd = nIndex;
  1823. }
  1824. if(CS.nTicks > nSearchBegin)
  1825. {
  1826. nContextSwitchStart = nIndex;
  1827. }
  1828. }
  1829. *pContextSwitchStart = nContextSwitchStart;
  1830. *pContextSwitchEnd = nContextSwitchEnd;
  1831. }
  1832. #if MICROPROFILE_WEBSERVER
  1833. #define MICROPROFILE_EMBED_HTML
  1834. extern const char* g_MicroProfileHtml_begin[];
  1835. extern size_t g_MicroProfileHtml_begin_sizes[];
  1836. extern size_t g_MicroProfileHtml_begin_count;
  1837. extern const char* g_MicroProfileHtml_end[];
  1838. extern size_t g_MicroProfileHtml_end_sizes[];
  1839. extern size_t g_MicroProfileHtml_end_count;
  1840. typedef void MicroProfileWriteCallback(void* Handle, size_t size, const char* pData);
  1841. uint32_t MicroProfileWebServerPort()
  1842. {
  1843. return S.nWebServerPort;
  1844. }
  1845. void MicroProfileDumpFile(const char* pHtml, const char* pCsv)
  1846. {
  1847. S.nDumpFileNextFrame = 0;
  1848. if(pHtml)
  1849. {
  1850. uint32_t nLen = strlen(pHtml);
  1851. if(nLen > sizeof(S.HtmlDumpPath)-1)
  1852. {
  1853. return;
  1854. }
  1855. memcpy(S.HtmlDumpPath, pHtml, nLen+1);
  1856. S.nDumpFileNextFrame |= 1;
  1857. }
  1858. if(pCsv)
  1859. {
  1860. uint32_t nLen = strlen(pCsv);
  1861. if(nLen > sizeof(S.CsvDumpPath)-1)
  1862. {
  1863. return;
  1864. }
  1865. memcpy(S.CsvDumpPath, pCsv, nLen+1);
  1866. S.nDumpFileNextFrame |= 2;
  1867. }
  1868. }
  1869. void MicroProfilePrintf(MicroProfileWriteCallback CB, void* Handle, const char* pFmt, ...)
  1870. {
  1871. char buffer[32*1024];
  1872. va_list args;
  1873. va_start (args, pFmt);
  1874. #ifdef _WIN32
  1875. size_t size = vsprintf_s(buffer, pFmt, args);
  1876. #else
  1877. size_t size = vsnprintf(buffer, sizeof(buffer)-1, pFmt, args);
  1878. #endif
  1879. CB(Handle, size, &buffer[0]);
  1880. va_end (args);
  1881. }
  1882. #define printf(...) MicroProfilePrintf(CB, Handle, __VA_ARGS__)
  1883. void MicroProfileDumpCsv(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames)
  1884. {
  1885. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  1886. float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  1887. float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu());
  1888. printf("frames,%d\n", nAggregateFrames);
  1889. printf("group,name,average,max,callaverage\n");
  1890. uint32_t nNumTimers = S.nTotalTimers;
  1891. uint32_t nBlockSize = 2 * nNumTimers;
  1892. float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float));
  1893. float* pAverage = pTimers + nBlockSize;
  1894. float* pMax = pTimers + 2 * nBlockSize;
  1895. float* pCallAverage = pTimers + 3 * nBlockSize;
  1896. float* pTimersExclusive = pTimers + 4 * nBlockSize;
  1897. float* pAverageExclusive = pTimers + 5 * nBlockSize;
  1898. float* pMaxExclusive = pTimers + 6 * nBlockSize;
  1899. float* pTotal = pTimers + 7 * nBlockSize;
  1900. MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers);
  1901. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1902. {
  1903. uint32_t nIdx = i * 2;
  1904. printf("\"%s\",\"%s\",%f,%f,%f\n", S.TimerInfo[i].pName, S.GroupInfo[S.TimerInfo[i].nGroupIndex].pName, pAverage[nIdx], pMax[nIdx], pCallAverage[nIdx]);
  1905. }
  1906. printf("\n\n");
  1907. printf("group,average,max,total\n");
  1908. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1909. {
  1910. const char* pGroupName = S.GroupInfo[j].pName;
  1911. float fToMs = S.GroupInfo[j].Type == MicroProfileTokenTypeGpu ? fToMsGPU : fToMsCPU;
  1912. if(pGroupName[0] != '\0')
  1913. {
  1914. printf("\"%s\",%.3f,%.3f,%.3f\n", pGroupName, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j]);
  1915. }
  1916. }
  1917. printf("\n\n");
  1918. printf("group,thread,average,total\n");
  1919. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1920. {
  1921. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  1922. {
  1923. if(S.Pool[i])
  1924. {
  1925. const char* pThreadName = &S.Pool[i]->ThreadName[0];
  1926. // MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i);
  1927. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  1928. {
  1929. uint64_t nTicks = S.Pool[i]->nAggregateGroupTicks[j];
  1930. float fTime = nTicks / nAggregateFrames * fToMs;
  1931. float fTimeTotal = nTicks * fToMs;
  1932. if(fTimeTotal > 0.01f)
  1933. {
  1934. const char* pGroupName = S.GroupInfo[j].pName;
  1935. printf("\"%s\",\"%s\",%.3f,%.3f\n", pGroupName, pThreadName, fTime, fTimeTotal);
  1936. }
  1937. }
  1938. }
  1939. }
  1940. }
  1941. printf("\n\n");
  1942. printf("frametimecpu\n");
  1943. const uint32_t nCount = MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3;
  1944. const uint32_t nStart = S.nFrameCurrent;
  1945. for(uint32_t i = nCount; i > 0; i--)
  1946. {
  1947. uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY;
  1948. uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1949. uint64_t nTicks = S.Frames[nFrameNext].nFrameStartCpu - S.Frames[nFrame].nFrameStartCpu;
  1950. printf("%f,", nTicks * fToMsCPU);
  1951. }
  1952. printf("\n");
  1953. printf("\n\n");
  1954. printf("frametimegpu\n");
  1955. for(uint32_t i = nCount; i > 0; i--)
  1956. {
  1957. uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY;
  1958. uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1959. uint64_t nTicks = S.Frames[nFrameNext].nFrameStartGpu - S.Frames[nFrame].nFrameStartGpu;
  1960. printf("%f,", nTicks * fToMsGPU);
  1961. }
  1962. printf("\n\n");
  1963. printf("Meta\n");//only single frame snapshot
  1964. printf("name,average,max,total\n");
  1965. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  1966. {
  1967. if(S.MetaCounters[j].pName)
  1968. {
  1969. printf("\"%s\",%f,%lld,%lld\n",S.MetaCounters[j].pName, S.MetaCounters[j].nSumAggregate / (float)nAggregateFrames, S.MetaCounters[j].nSumAggregateMax,S.MetaCounters[j].nSumAggregate);
  1970. }
  1971. }
  1972. }
  1973. #undef printf
  1974. void MicroProfileDumpHtml(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames, const char* pHost)
  1975. {
  1976. uint32_t nRunning = S.nRunning;
  1977. S.nRunning = 0;
  1978. //stall pushing of timers
  1979. uint64_t nActiveGroup = S.nActiveGroup;
  1980. S.nActiveGroup = 0;
  1981. S.nPauseTicks = MP_TICK();
  1982. for(size_t i = 0; i < g_MicroProfileHtml_begin_count; ++i)
  1983. {
  1984. CB(Handle, g_MicroProfileHtml_begin_sizes[i]-1, g_MicroProfileHtml_begin[i]);
  1985. }
  1986. //dump info
  1987. uint64_t nTicks = MP_TICK();
  1988. float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  1989. float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu());
  1990. float fAggregateMs = fToMsCPU * (nTicks - S.nAggregateFlipTick);
  1991. MicroProfilePrintf(CB, Handle, "var DumpHost = '%s';\n", pHost ? pHost : "");
  1992. time_t CaptureTime;
  1993. time(&CaptureTime);
  1994. MicroProfilePrintf(CB, Handle, "var DumpUtcCaptureTime = %ld;\n", CaptureTime);
  1995. MicroProfilePrintf(CB, Handle, "var AggregateInfo = {'Frames':%d, 'Time':%f};\n", S.nAggregateFrames, fAggregateMs);
  1996. //categories
  1997. MicroProfilePrintf(CB, Handle, "var CategoryInfo = Array(%d);\n",S.nCategoryCount);
  1998. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1999. {
  2000. MicroProfilePrintf(CB, Handle, "CategoryInfo[%d] = \"%s\";\n", i, S.CategoryInfo[i].pName);
  2001. }
  2002. //groups
  2003. MicroProfilePrintf(CB, Handle, "var GroupInfo = Array(%d);\n\n",S.nGroupCount);
  2004. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  2005. float fRcpAggregateFrames = 1.f / nAggregateFrames;
  2006. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2007. {
  2008. MP_ASSERT(i == S.GroupInfo[i].nGroupIndex);
  2009. float fToMs = S.GroupInfo[i].Type == MicroProfileTokenTypeCpu ? fToMsCPU : fToMsGPU;
  2010. MicroProfilePrintf(CB, Handle, "GroupInfo[%d] = MakeGroup(%d, \"%s\", %d, %d, %d, %f, %f, %f, '#%02x%02x%02x');\n",
  2011. S.GroupInfo[i].nGroupIndex,
  2012. S.GroupInfo[i].nGroupIndex,
  2013. S.GroupInfo[i].pName,
  2014. S.GroupInfo[i].nCategory,
  2015. S.GroupInfo[i].nNumTimers,
  2016. S.GroupInfo[i].Type == MicroProfileTokenTypeGpu?1:0,
  2017. fToMs * S.AggregateGroup[i],
  2018. fToMs * S.AggregateGroup[i] / nAggregateFrames,
  2019. fToMs * S.AggregateGroupMax[i],
  2020. MICROPROFILE_UNPACK_RED(S.GroupInfo[i].nColor) & 0xff,
  2021. MICROPROFILE_UNPACK_GREEN(S.GroupInfo[i].nColor) & 0xff,
  2022. MICROPROFILE_UNPACK_BLUE(S.GroupInfo[i].nColor) & 0xff);
  2023. }
  2024. //timers
  2025. uint32_t nNumTimers = S.nTotalTimers;
  2026. uint32_t nBlockSize = 2 * nNumTimers;
  2027. float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float));
  2028. float* pAverage = pTimers + nBlockSize;
  2029. float* pMax = pTimers + 2 * nBlockSize;
  2030. float* pCallAverage = pTimers + 3 * nBlockSize;
  2031. float* pTimersExclusive = pTimers + 4 * nBlockSize;
  2032. float* pAverageExclusive = pTimers + 5 * nBlockSize;
  2033. float* pMaxExclusive = pTimers + 6 * nBlockSize;
  2034. float* pTotal = pTimers + 7 * nBlockSize;
  2035. MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers);
  2036. MicroProfilePrintf(CB, Handle, "\nvar TimerInfo = Array(%d);\n\n", S.nTotalTimers);
  2037. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2038. {
  2039. uint32_t nIdx = i * 2;
  2040. MP_ASSERT(i == S.TimerInfo[i].nTimerIndex);
  2041. MicroProfilePrintf(CB, Handle, "var Meta%d = [", i);
  2042. bool bOnce = true;
  2043. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2044. {
  2045. if(S.MetaCounters[j].pName)
  2046. {
  2047. uint32_t lala = S.MetaCounters[j].nCounters[i];
  2048. MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", lala);
  2049. bOnce = false;
  2050. }
  2051. }
  2052. MicroProfilePrintf(CB, Handle, "];\n");
  2053. MicroProfilePrintf(CB, Handle, "var MetaAvg%d = [", i);
  2054. bOnce = true;
  2055. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2056. {
  2057. if(S.MetaCounters[j].pName)
  2058. {
  2059. MicroProfilePrintf(CB, Handle, bOnce ? "%f" : ",%f", fRcpAggregateFrames * S.MetaCounters[j].nAggregate[i]);
  2060. bOnce = false;
  2061. }
  2062. }
  2063. MicroProfilePrintf(CB, Handle, "];\n");
  2064. MicroProfilePrintf(CB, Handle, "var MetaMax%d = [", i);
  2065. bOnce = true;
  2066. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2067. {
  2068. if(S.MetaCounters[j].pName)
  2069. {
  2070. MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", S.MetaCounters[j].nAggregateMax[i]);
  2071. bOnce = false;
  2072. }
  2073. }
  2074. MicroProfilePrintf(CB, Handle, "];\n");
  2075. uint32_t nColor = S.TimerInfo[i].nColor;
  2076. uint32_t nColorDark = (nColor >> 1) & ~0x80808080;
  2077. MicroProfilePrintf(CB, Handle, "TimerInfo[%d] = MakeTimer(%d, \"%s\", %d, '#%02x%02x%02x','#%02x%02x%02x', %f, %f, %f, %f, %f, %d, %f, Meta%d, MetaAvg%d, MetaMax%d);\n", S.TimerInfo[i].nTimerIndex, S.TimerInfo[i].nTimerIndex, S.TimerInfo[i].pName, S.TimerInfo[i].nGroupIndex,
  2078. MICROPROFILE_UNPACK_RED(nColor) & 0xff,
  2079. MICROPROFILE_UNPACK_GREEN(nColor) & 0xff,
  2080. MICROPROFILE_UNPACK_BLUE(nColor) & 0xff,
  2081. MICROPROFILE_UNPACK_RED(nColorDark) & 0xff,
  2082. MICROPROFILE_UNPACK_GREEN(nColorDark) & 0xff,
  2083. MICROPROFILE_UNPACK_BLUE(nColorDark) & 0xff,
  2084. pAverage[nIdx],
  2085. pMax[nIdx],
  2086. pAverageExclusive[nIdx],
  2087. pMaxExclusive[nIdx],
  2088. pCallAverage[nIdx],
  2089. S.Aggregate[i].nCount,
  2090. pTotal[nIdx],
  2091. i,i,i);
  2092. }
  2093. MicroProfilePrintf(CB, Handle, "\nvar ThreadNames = [");
  2094. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2095. {
  2096. if(S.Pool[i])
  2097. {
  2098. MicroProfilePrintf(CB, Handle, "'%s',", S.Pool[i]->ThreadName);
  2099. }
  2100. else
  2101. {
  2102. MicroProfilePrintf(CB, Handle, "'Thread %d',", i);
  2103. }
  2104. }
  2105. MicroProfilePrintf(CB, Handle, "];\n\n");
  2106. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2107. {
  2108. if(S.Pool[i])
  2109. {
  2110. MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i);
  2111. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  2112. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  2113. {
  2114. MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j]/nAggregateFrames * fToMs);
  2115. }
  2116. MicroProfilePrintf(CB, Handle, "];\n");
  2117. }
  2118. }
  2119. MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeArray = [");
  2120. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2121. {
  2122. if(S.Pool[i])
  2123. {
  2124. MicroProfilePrintf(CB, Handle, "ThreadGroupTime%d,", i);
  2125. }
  2126. }
  2127. MicroProfilePrintf(CB, Handle, "];\n");
  2128. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2129. {
  2130. if(S.Pool[i])
  2131. {
  2132. MicroProfilePrintf(CB, Handle, "var ThreadGroupTimeTotal%d = [", i);
  2133. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  2134. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  2135. {
  2136. MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j] * fToMs);
  2137. }
  2138. MicroProfilePrintf(CB, Handle, "];\n");
  2139. }
  2140. }
  2141. MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeTotalArray = [");
  2142. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2143. {
  2144. if(S.Pool[i])
  2145. {
  2146. MicroProfilePrintf(CB, Handle, "ThreadGroupTimeTotal%d,", i);
  2147. }
  2148. }
  2149. MicroProfilePrintf(CB, Handle, "];");
  2150. MicroProfilePrintf(CB, Handle, "\nvar ThreadIds = [");
  2151. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2152. {
  2153. if(S.Pool[i])
  2154. {
  2155. ThreadIdType ThreadId = S.Pool[i]->nThreadId;
  2156. if(!ThreadId)
  2157. {
  2158. ThreadId = (ThreadIdType)-1;
  2159. }
  2160. MicroProfilePrintf(CB, Handle, "%d,", ThreadId);
  2161. }
  2162. else
  2163. {
  2164. MicroProfilePrintf(CB, Handle, "-1,", i);
  2165. }
  2166. }
  2167. MicroProfilePrintf(CB, Handle, "];\n\n");
  2168. MicroProfilePrintf(CB, Handle, "\nvar MetaNames = [");
  2169. for(int i = 0; i < MICROPROFILE_META_MAX; ++i)
  2170. {
  2171. if(S.MetaCounters[i].pName)
  2172. {
  2173. MicroProfilePrintf(CB, Handle, "'%s',", S.MetaCounters[i].pName);
  2174. }
  2175. }
  2176. MicroProfilePrintf(CB, Handle, "];\n\n");
  2177. uint32_t nNumFrames = (MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3); //leave a few to not overwrite
  2178. nNumFrames = MicroProfileMin(nNumFrames, (uint32_t)nMaxFrames);
  2179. uint32_t nFirstFrame = (S.nFrameCurrent + MICROPROFILE_MAX_FRAME_HISTORY - nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY;
  2180. uint32_t nLastFrame = (nFirstFrame + nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY;
  2181. MP_ASSERT(nLastFrame == (S.nFrameCurrent % MICROPROFILE_MAX_FRAME_HISTORY));
  2182. MP_ASSERT(nFirstFrame < MICROPROFILE_MAX_FRAME_HISTORY);
  2183. MP_ASSERT(nLastFrame < MICROPROFILE_MAX_FRAME_HISTORY);
  2184. const int64_t nTickStart = S.Frames[nFirstFrame].nFrameStartCpu;
  2185. const int64_t nTickEnd = S.Frames[nLastFrame].nFrameStartCpu;
  2186. int64_t nTickStartGpu = S.Frames[nFirstFrame].nFrameStartGpu;
  2187. int64_t nTickReferenceCpu, nTickReferenceGpu;
  2188. int64_t nTicksPerSecondCpu = MicroProfileTicksPerSecondCpu();
  2189. int64_t nTicksPerSecondGpu = MicroProfileTicksPerSecondGpu();
  2190. int nTickReference = 0;
  2191. if(MicroProfileGetGpuTickReference(&nTickReferenceCpu, &nTickReferenceGpu))
  2192. {
  2193. nTickStartGpu = (nTickStart - nTickReferenceCpu) * nTicksPerSecondGpu / nTicksPerSecondCpu + nTickReferenceGpu;
  2194. nTickReference = 1;
  2195. }
  2196. #if MICROPROFILE_DEBUG
  2197. printf("dumping %d frames\n", nNumFrames);
  2198. printf("dumping frame %d to %d\n", nFirstFrame, nLastFrame);
  2199. #endif
  2200. uint32_t* nTimerCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers);
  2201. memset(nTimerCounter, 0, sizeof(uint32_t) * S.nTotalTimers);
  2202. MicroProfilePrintf(CB, Handle, "var Frames = Array(%d);\n", nNumFrames);
  2203. for(uint32_t i = 0; i < nNumFrames; ++i)
  2204. {
  2205. uint32_t nFrameIndex = (nFirstFrame + i) % MICROPROFILE_MAX_FRAME_HISTORY;
  2206. uint32_t nFrameIndexNext = (nFrameIndex + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  2207. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2208. {
  2209. MicroProfileThreadLog* pLog = S.Pool[j];
  2210. int64_t nStartTickBase = pLog->nGpu ? nTickStartGpu : nTickStart;
  2211. uint32_t nLogStart = S.Frames[nFrameIndex].nLogStart[j];
  2212. uint32_t nLogEnd = S.Frames[nFrameIndexNext].nLogStart[j];
  2213. float fToMsCpu = MicroProfileTickToMsMultiplier(nTicksPerSecondCpu);
  2214. float fToMsBase = MicroProfileTickToMsMultiplier(pLog->nGpu ? nTicksPerSecondGpu : nTicksPerSecondCpu);
  2215. MicroProfilePrintf(CB, Handle, "var ts_%d_%d = [", i, j);
  2216. if(nLogStart != nLogEnd)
  2217. {
  2218. uint32_t k = nLogStart;
  2219. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2220. float fToMs = nLogType == MP_LOG_GPU_EXTRA ? fToMsCpu : fToMsBase;
  2221. int64_t nStartTick = nLogType == MP_LOG_GPU_EXTRA ? nTickStart : nStartTickBase;
  2222. float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs;
  2223. MicroProfilePrintf(CB, Handle, "%f", fTime);
  2224. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2225. {
  2226. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2227. float fToMs = nLogType == MP_LOG_GPU_EXTRA ? fToMsCpu : fToMsBase;
  2228. nStartTick = nLogType == MP_LOG_GPU_EXTRA ? nTickStart : nStartTickBase;
  2229. float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs;
  2230. MicroProfilePrintf(CB, Handle, ",%f", fTime);
  2231. }
  2232. }
  2233. MicroProfilePrintf(CB, Handle, "];\n");
  2234. MicroProfilePrintf(CB, Handle, "var tt_%d_%d = [", i, j);
  2235. if(nLogStart != nLogEnd)
  2236. {
  2237. uint32_t k = nLogStart;
  2238. MicroProfilePrintf(CB, Handle, "%d", MicroProfileLogType(pLog->Log[k]));
  2239. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2240. {
  2241. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2242. if(nLogType == MP_LOG_META)
  2243. {
  2244. //for meta, store the count + 3, which is the tick part
  2245. nLogType = 3 + MicroProfileLogGetTick(pLog->Log[k]);
  2246. }
  2247. MicroProfilePrintf(CB, Handle, ",%d", nLogType);
  2248. }
  2249. }
  2250. MicroProfilePrintf(CB, Handle, "];\n");
  2251. MicroProfilePrintf(CB, Handle, "var ti_%d_%d = [", i, j);
  2252. if(nLogStart != nLogEnd)
  2253. {
  2254. uint32_t k = nLogStart;
  2255. MicroProfilePrintf(CB, Handle, "%d", (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]));
  2256. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2257. {
  2258. uint32_t nTimerIndex = (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]);
  2259. MicroProfilePrintf(CB, Handle, ",%d", nTimerIndex);
  2260. nTimerCounter[nTimerIndex]++;
  2261. }
  2262. }
  2263. MicroProfilePrintf(CB, Handle, "];\n");
  2264. }
  2265. MicroProfilePrintf(CB, Handle, "var ts%d = [", i);
  2266. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2267. {
  2268. MicroProfilePrintf(CB, Handle, "ts_%d_%d,", i, j);
  2269. }
  2270. MicroProfilePrintf(CB, Handle, "];\n");
  2271. MicroProfilePrintf(CB, Handle, "var tt%d = [", i);
  2272. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2273. {
  2274. MicroProfilePrintf(CB, Handle, "tt_%d_%d,", i, j);
  2275. }
  2276. MicroProfilePrintf(CB, Handle, "];\n");
  2277. MicroProfilePrintf(CB, Handle, "var ti%d = [", i);
  2278. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2279. {
  2280. MicroProfilePrintf(CB, Handle, "ti_%d_%d,", i, j);
  2281. }
  2282. MicroProfilePrintf(CB, Handle, "];\n");
  2283. int64_t nFrameStart = S.Frames[nFrameIndex].nFrameStartCpu;
  2284. int64_t nFrameEnd = S.Frames[nFrameIndexNext].nFrameStartCpu;
  2285. float fToMs = MicroProfileTickToMsMultiplier(nTicksPerSecondCpu);
  2286. float fFrameMs = MicroProfileLogTickDifference(nTickStart, nFrameStart) * fToMs;
  2287. float fFrameEndMs = MicroProfileLogTickDifference(nTickStart, nFrameEnd) * fToMs;
  2288. float fFrameGpuMs = 0;
  2289. float fFrameGpuEndMs = 0;
  2290. if(nTickReference)
  2291. {
  2292. fFrameGpuMs = MicroProfileLogTickDifference(nTickStartGpu, S.Frames[nFrameIndex].nFrameStartGpu) * fToMsGPU;
  2293. fFrameGpuEndMs = MicroProfileLogTickDifference(nTickStartGpu, S.Frames[nFrameIndexNext].nFrameStartGpu) * fToMsGPU;
  2294. }
  2295. MicroProfilePrintf(CB, Handle, "Frames[%d] = MakeFrame(%d, %f, %f, %f, %f, ts%d, tt%d, ti%d);\n", i, 0, fFrameMs, fFrameEndMs, fFrameGpuMs, fFrameGpuEndMs, i, i, i);
  2296. }
  2297. uint32_t nContextSwitchStart = 0;
  2298. uint32_t nContextSwitchEnd = 0;
  2299. MicroProfileContextSwitchSearch(&nContextSwitchStart, &nContextSwitchEnd, nTickStart, nTickEnd);
  2300. uint32_t nWrittenBefore = S.nWebServerDataSent;
  2301. MicroProfilePrintf(CB, Handle, "var CSwitchThreadInOutCpu = [");
  2302. for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE)
  2303. {
  2304. MicroProfileContextSwitch CS = S.ContextSwitch[j];
  2305. int nCpu = CS.nCpu;
  2306. MicroProfilePrintf(CB, Handle, "%d,%d,%d,", CS.nThreadIn, CS.nThreadOut, nCpu);
  2307. }
  2308. MicroProfilePrintf(CB, Handle, "];\n");
  2309. MicroProfilePrintf(CB, Handle, "var CSwitchTime = [");
  2310. float fToMsCpu = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  2311. for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE)
  2312. {
  2313. MicroProfileContextSwitch CS = S.ContextSwitch[j];
  2314. float fTime = MicroProfileLogTickDifference(nTickStart, CS.nTicks) * fToMsCpu;
  2315. MicroProfilePrintf(CB, Handle, "%f,", fTime);
  2316. }
  2317. MicroProfilePrintf(CB, Handle, "];\n");
  2318. uint32_t nWrittenAfter = S.nWebServerDataSent;
  2319. MicroProfilePrintf(CB, Handle, "//CSwitch Size %d\n", nWrittenAfter - nWrittenBefore);
  2320. for(size_t i = 0; i < g_MicroProfileHtml_end_count; ++i)
  2321. {
  2322. CB(Handle, g_MicroProfileHtml_end_sizes[i]-1, g_MicroProfileHtml_end[i]);
  2323. }
  2324. uint32_t* nGroupCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount);
  2325. memset(nGroupCounter, 0, sizeof(uint32_t) * S.nGroupCount);
  2326. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2327. {
  2328. uint32_t nGroupIndex = S.TimerInfo[i].nGroupIndex;
  2329. nGroupCounter[nGroupIndex] += nTimerCounter[i];
  2330. }
  2331. uint32_t* nGroupCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount);
  2332. uint32_t* nTimerCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers);
  2333. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2334. {
  2335. nGroupCounterSort[i] = i;
  2336. }
  2337. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2338. {
  2339. nTimerCounterSort[i] = i;
  2340. }
  2341. std::sort(nGroupCounterSort, nGroupCounterSort + S.nGroupCount,
  2342. [nGroupCounter](const uint32_t l, const uint32_t r)
  2343. {
  2344. return nGroupCounter[l] > nGroupCounter[r];
  2345. }
  2346. );
  2347. std::sort(nTimerCounterSort, nTimerCounterSort + S.nTotalTimers,
  2348. [nTimerCounter](const uint32_t l, const uint32_t r)
  2349. {
  2350. return nTimerCounter[l] > nTimerCounter[r];
  2351. }
  2352. );
  2353. MicroProfilePrintf(CB, Handle, "\n<!--\nMarker Per Group\n");
  2354. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2355. {
  2356. uint32_t idx = nGroupCounterSort[i];
  2357. MicroProfilePrintf(CB, Handle, "%8d:%s\n", nGroupCounter[idx], S.GroupInfo[idx].pName);
  2358. }
  2359. MicroProfilePrintf(CB, Handle, "Marker Per Timer\n");
  2360. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2361. {
  2362. uint32_t idx = nTimerCounterSort[i];
  2363. MicroProfilePrintf(CB, Handle, "%8d:%s(%s)\n", nTimerCounter[idx], S.TimerInfo[idx].pName, S.GroupInfo[S.TimerInfo[idx].nGroupIndex].pName);
  2364. }
  2365. MicroProfilePrintf(CB, Handle, "\n-->\n");
  2366. S.nActiveGroup = nActiveGroup;
  2367. S.nRunning = nRunning;
  2368. #if MICROPROFILE_DEBUG
  2369. int64_t nTicksEnd = MP_TICK();
  2370. float fMs = fToMsCpu * (nTicksEnd - S.nPauseTicks);
  2371. printf("html dump took %6.2fms\n", fMs);
  2372. #endif
  2373. }
  2374. void MicroProfileWriteFile(void* Handle, size_t nSize, const char* pData)
  2375. {
  2376. fwrite(pData, nSize, 1, (FILE*)Handle);
  2377. }
  2378. void MicroProfileDumpToFile()
  2379. {
  2380. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  2381. if(S.nDumpFileNextFrame&1)
  2382. {
  2383. FILE* F = fopen(S.HtmlDumpPath, "w");
  2384. if(F)
  2385. {
  2386. MicroProfileDumpHtml(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES, S.HtmlDumpPath);
  2387. fclose(F);
  2388. }
  2389. }
  2390. if(S.nDumpFileNextFrame&2)
  2391. {
  2392. FILE* F = fopen(S.CsvDumpPath, "w");
  2393. if(F)
  2394. {
  2395. MicroProfileDumpCsv(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES);
  2396. fclose(F);
  2397. }
  2398. }
  2399. }
  2400. void MicroProfileFlushSocket(MpSocket Socket)
  2401. {
  2402. send(Socket, &S.WebServerBuffer[0], S.WebServerPut, 0);
  2403. S.WebServerPut = 0;
  2404. }
  2405. void MicroProfileWriteSocket(void* Handle, size_t nSize, const char* pData)
  2406. {
  2407. S.nWebServerDataSent += nSize;
  2408. MpSocket Socket = *(MpSocket*)Handle;
  2409. if(nSize > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE / 2)
  2410. {
  2411. MicroProfileFlushSocket(Socket);
  2412. send(Socket, pData, nSize, 0);
  2413. }
  2414. else
  2415. {
  2416. memcpy(&S.WebServerBuffer[S.WebServerPut], pData, nSize);
  2417. S.WebServerPut += nSize;
  2418. if(S.WebServerPut > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE/2)
  2419. {
  2420. MicroProfileFlushSocket(Socket);
  2421. }
  2422. }
  2423. }
  2424. #if MICROPROFILE_MINIZ
  2425. #ifndef MICROPROFILE_COMPRESS_BUFFER_SIZE
  2426. #define MICROPROFILE_COMPRESS_BUFFER_SIZE (256<<10)
  2427. #endif
  2428. #define MICROPROFILE_COMPRESS_CHUNK (MICROPROFILE_COMPRESS_BUFFER_SIZE/2)
  2429. struct MicroProfileCompressedSocketState
  2430. {
  2431. unsigned char DeflateOut[MICROPROFILE_COMPRESS_CHUNK];
  2432. unsigned char DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2433. mz_stream Stream;
  2434. MpSocket Socket;
  2435. uint32_t nSize;
  2436. uint32_t nCompressedSize;
  2437. uint32_t nFlushes;
  2438. uint32_t nMemmoveBytes;
  2439. };
  2440. void MicroProfileCompressedSocketFlush(MicroProfileCompressedSocketState* pState)
  2441. {
  2442. mz_stream& Stream = pState->Stream;
  2443. unsigned char* pSendStart = &pState->DeflateOut[0];
  2444. unsigned char* pSendEnd = &pState->DeflateOut[MICROPROFILE_COMPRESS_CHUNK - Stream.avail_out];
  2445. if(pSendStart != pSendEnd)
  2446. {
  2447. send(pState->Socket, (const char*)pSendStart, pSendEnd - pSendStart, 0);
  2448. pState->nCompressedSize += pSendEnd - pSendStart;
  2449. }
  2450. Stream.next_out = &pState->DeflateOut[0];
  2451. Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK;
  2452. }
  2453. void MicroProfileCompressedSocketStart(MicroProfileCompressedSocketState* pState, MpSocket Socket)
  2454. {
  2455. mz_stream& Stream = pState->Stream;
  2456. memset(&Stream, 0, sizeof(Stream));
  2457. Stream.next_out = &pState->DeflateOut[0];
  2458. Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK;
  2459. Stream.next_in = &pState->DeflateIn[0];
  2460. Stream.avail_in = 0;
  2461. mz_deflateInit(&Stream, Z_DEFAULT_COMPRESSION);
  2462. pState->Socket = Socket;
  2463. pState->nSize = 0;
  2464. pState->nCompressedSize = 0;
  2465. pState->nFlushes = 0;
  2466. pState->nMemmoveBytes = 0;
  2467. }
  2468. void MicroProfileCompressedSocketFinish(MicroProfileCompressedSocketState* pState)
  2469. {
  2470. mz_stream& Stream = pState->Stream;
  2471. MicroProfileCompressedSocketFlush(pState);
  2472. int r = mz_deflate(&Stream, MZ_FINISH);
  2473. MP_ASSERT(r == MZ_STREAM_END);
  2474. MicroProfileCompressedSocketFlush(pState);
  2475. r = mz_deflateEnd(&Stream);
  2476. MP_ASSERT(r == MZ_OK);
  2477. }
  2478. void MicroProfileCompressedWriteSocket(void* Handle, size_t nSize, const char* pData)
  2479. {
  2480. MicroProfileCompressedSocketState* pState = (MicroProfileCompressedSocketState*)Handle;
  2481. mz_stream& Stream = pState->Stream;
  2482. const unsigned char* pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2483. const unsigned char* pDeflateInStart = &pState->DeflateIn[0];
  2484. const unsigned char* pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2485. pState->nSize += nSize;
  2486. if(nSize <= pDeflateInRealEnd - pDeflateInEnd)
  2487. {
  2488. memcpy((void*)pDeflateInEnd, pData, nSize);
  2489. Stream.avail_in += nSize;
  2490. MP_ASSERT(Stream.next_in + Stream.avail_in <= pDeflateInRealEnd);
  2491. return;
  2492. }
  2493. int Flush = 0;
  2494. while(nSize)
  2495. {
  2496. pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2497. if(Flush)
  2498. {
  2499. pState->nFlushes++;
  2500. MicroProfileCompressedSocketFlush(pState);
  2501. pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2502. if(pDeflateInEnd == pDeflateInRealEnd)
  2503. {
  2504. if(Stream.avail_in)
  2505. {
  2506. MP_ASSERT(pDeflateInStart != Stream.next_in);
  2507. memmove((void*)pDeflateInStart, Stream.next_in, Stream.avail_in);
  2508. pState->nMemmoveBytes += Stream.avail_in;
  2509. }
  2510. Stream.next_in = pDeflateInStart;
  2511. pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2512. }
  2513. }
  2514. size_t nSpace = pDeflateInRealEnd - pDeflateInEnd;
  2515. size_t nBytes = MicroProfileMin(nSpace, nSize);
  2516. MP_ASSERT(nBytes + pDeflateInEnd <= pDeflateInRealEnd);
  2517. memcpy((void*)pDeflateInEnd, pData, nBytes);
  2518. Stream.avail_in += nBytes;
  2519. nSize -= nBytes;
  2520. pData += nBytes;
  2521. int r = mz_deflate(&Stream, MZ_NO_FLUSH);
  2522. Flush = r == MZ_BUF_ERROR || nBytes == 0 || Stream.avail_out == 0 ? 1 : 0;
  2523. MP_ASSERT(r == MZ_BUF_ERROR || r == MZ_OK);
  2524. if(r == MZ_BUF_ERROR)
  2525. {
  2526. r = mz_deflate(&Stream, MZ_SYNC_FLUSH);
  2527. }
  2528. }
  2529. }
  2530. #endif
  2531. #ifndef MicroProfileSetNonBlocking //fcntl doesnt work on a some unix like platforms..
  2532. void MicroProfileSetNonBlocking(MpSocket Socket, int NonBlocking)
  2533. {
  2534. #ifdef _WIN32
  2535. u_long nonBlocking = NonBlocking ? 1 : 0;
  2536. ioctlsocket(Socket, FIONBIO, &nonBlocking);
  2537. #else
  2538. int Options = fcntl(Socket, F_GETFL);
  2539. if(NonBlocking)
  2540. {
  2541. fcntl(Socket, F_SETFL, Options|O_NONBLOCK);
  2542. }
  2543. else
  2544. {
  2545. fcntl(Socket, F_SETFL, Options&(~O_NONBLOCK));
  2546. }
  2547. #endif
  2548. }
  2549. #endif
  2550. void MicroProfileWebServerStart()
  2551. {
  2552. #ifdef _WIN32
  2553. WSADATA wsa;
  2554. if(WSAStartup(MAKEWORD(2, 2), &wsa))
  2555. {
  2556. S.ListenerSocket = -1;
  2557. return;
  2558. }
  2559. #endif
  2560. S.ListenerSocket = socket(PF_INET, SOCK_STREAM, 6);
  2561. MP_ASSERT(!MP_INVALID_SOCKET(S.ListenerSocket));
  2562. MicroProfileSetNonBlocking(S.ListenerSocket, 1);
  2563. S.nWebServerPort = (uint32_t)-1;
  2564. struct sockaddr_in Addr;
  2565. Addr.sin_family = AF_INET;
  2566. Addr.sin_addr.s_addr = INADDR_ANY;
  2567. for(int i = 0; i < 20; ++i)
  2568. {
  2569. Addr.sin_port = htons(MICROPROFILE_WEBSERVER_PORT+i);
  2570. if(0 == bind(S.ListenerSocket, (sockaddr*)&Addr, sizeof(Addr)))
  2571. {
  2572. S.nWebServerPort = MICROPROFILE_WEBSERVER_PORT+i;
  2573. break;
  2574. }
  2575. }
  2576. listen(S.ListenerSocket, 8);
  2577. }
  2578. void MicroProfileWebServerStop()
  2579. {
  2580. #ifdef _WIN32
  2581. closesocket(S.ListenerSocket);
  2582. WSACleanup();
  2583. #else
  2584. close(S.ListenerSocket);
  2585. #endif
  2586. }
  2587. int MicroProfileParseGet(const char* pGet)
  2588. {
  2589. const char* pStart = pGet;
  2590. while(*pGet != '\0')
  2591. {
  2592. if(*pGet < '0' || *pGet > '9')
  2593. return 0;
  2594. pGet++;
  2595. }
  2596. int nFrames = atoi(pStart);
  2597. if(nFrames)
  2598. {
  2599. return nFrames;
  2600. }
  2601. else
  2602. {
  2603. return MICROPROFILE_WEBSERVER_MAXFRAMES;
  2604. }
  2605. }
  2606. bool MicroProfileWebServerUpdate()
  2607. {
  2608. MICROPROFILE_SCOPEI("MicroProfile", "Webserver-update", -1);
  2609. MpSocket Connection = accept(S.ListenerSocket, 0, 0);
  2610. bool bServed = false;
  2611. if(!MP_INVALID_SOCKET(Connection))
  2612. {
  2613. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  2614. char Req[8192];
  2615. MicroProfileSetNonBlocking(Connection, 0);
  2616. int nReceived = recv(Connection, Req, sizeof(Req)-1, 0);
  2617. if(nReceived > 0)
  2618. {
  2619. Req[nReceived] = '\0';
  2620. #if MICROPROFILE_MINIZ
  2621. #define MICROPROFILE_HTML_HEADER "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Encoding: deflate\r\nExpires: Tue, 01 Jan 2199 16:00:00 GMT\r\n\r\n"
  2622. #else
  2623. #define MICROPROFILE_HTML_HEADER "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nExpires: Tue, 01 Jan 2199 16:00:00 GMT\r\n\r\n"
  2624. #endif
  2625. char* pHttp = strstr(Req, "HTTP/");
  2626. char* pGet = strstr(Req, "GET /");
  2627. char* pHost = strstr(Req, "Host: ");
  2628. auto Terminate = [](char* pString)
  2629. {
  2630. char* pEnd = pString;
  2631. while(*pEnd != '\0')
  2632. {
  2633. if(*pEnd == '\r' || *pEnd == '\n' || *pEnd == ' ')
  2634. {
  2635. *pEnd = '\0';
  2636. return;
  2637. }
  2638. pEnd++;
  2639. }
  2640. };
  2641. if(pHost)
  2642. {
  2643. pHost += sizeof("Host: ")-1;
  2644. Terminate(pHost);
  2645. }
  2646. if(pHttp && pGet)
  2647. {
  2648. *pHttp = '\0';
  2649. pGet += sizeof("GET /")-1;
  2650. Terminate(pGet);
  2651. int nFrames = MicroProfileParseGet(pGet);
  2652. if(nFrames)
  2653. {
  2654. uint64_t nTickStart = MP_TICK();
  2655. send(Connection, MICROPROFILE_HTML_HEADER, sizeof(MICROPROFILE_HTML_HEADER)-1, 0);
  2656. uint64_t nDataStart = S.nWebServerDataSent;
  2657. S.WebServerPut = 0;
  2658. #if 0 == MICROPROFILE_MINIZ
  2659. MicroProfileDumpHtml(MicroProfileWriteSocket, &Connection, nFrames, pHost);
  2660. uint64_t nDataEnd = S.nWebServerDataSent;
  2661. uint64_t nTickEnd = MP_TICK();
  2662. uint64_t nDiff = (nTickEnd - nTickStart);
  2663. float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff;
  2664. int nKb = ((nDataEnd-nDataStart)>>10) + 1;
  2665. int nCompressedKb = nKb;
  2666. MicroProfilePrintf(MicroProfileWriteSocket, &Connection, "\n<!-- Sent %dkb in %.2fms-->\n\n",nKb, fMs);
  2667. MicroProfileFlushSocket(Connection);
  2668. #else
  2669. MicroProfileCompressedSocketState CompressState;
  2670. MicroProfileCompressedSocketStart(&CompressState, Connection);
  2671. MicroProfileDumpHtml(MicroProfileCompressedWriteSocket, &CompressState, nFrames, pHost);
  2672. S.nWebServerDataSent += CompressState.nSize;
  2673. uint64_t nDataEnd = S.nWebServerDataSent;
  2674. uint64_t nTickEnd = MP_TICK();
  2675. uint64_t nDiff = (nTickEnd - nTickStart);
  2676. float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff;
  2677. int nKb = ((nDataEnd-nDataStart)>>10) + 1;
  2678. int nCompressedKb = ((CompressState.nCompressedSize)>>10) + 1;
  2679. MicroProfilePrintf(MicroProfileCompressedWriteSocket, &CompressState, "\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs);
  2680. MicroProfileCompressedSocketFinish(&CompressState);
  2681. MicroProfileFlushSocket(Connection);
  2682. #endif
  2683. #if MICROPROFILE_DEBUG
  2684. printf("\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs);
  2685. #endif
  2686. }
  2687. }
  2688. }
  2689. #ifdef _WIN32
  2690. closesocket(Connection);
  2691. #else
  2692. close(Connection);
  2693. #endif
  2694. }
  2695. return bServed;
  2696. }
  2697. #endif
  2698. #if MICROPROFILE_CONTEXT_SWITCH_TRACE
  2699. //functions that need to be implemented per platform.
  2700. void* MicroProfileTraceThread(void* unused);
  2701. bool MicroProfileIsLocalThread(uint32_t nThreadId);
  2702. void MicroProfileStartContextSwitchTrace()
  2703. {
  2704. if(!S.bContextSwitchRunning)
  2705. {
  2706. S.bContextSwitchRunning = true;
  2707. S.bContextSwitchStop = false;
  2708. MicroProfileThreadStart(&S.ContextSwitchThread, MicroProfileTraceThread);
  2709. }
  2710. }
  2711. void MicroProfileStopContextSwitchTrace()
  2712. {
  2713. if(S.bContextSwitchRunning)
  2714. {
  2715. S.bContextSwitchStop = true;
  2716. MicroProfileThreadJoin(&S.ContextSwitchThread);
  2717. }
  2718. }
  2719. #ifdef _WIN32
  2720. #define INITGUID
  2721. #include <evntrace.h>
  2722. #include <evntcons.h>
  2723. #include <strsafe.h>
  2724. static GUID g_MicroProfileThreadClassGuid = { 0x3d6fa8d1, 0xfe05, 0x11d0, 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c };
  2725. struct MicroProfileSCSwitch
  2726. {
  2727. uint32_t NewThreadId;
  2728. uint32_t OldThreadId;
  2729. int8_t NewThreadPriority;
  2730. int8_t OldThreadPriority;
  2731. uint8_t PreviousCState;
  2732. int8_t SpareByte;
  2733. int8_t OldThreadWaitReason;
  2734. int8_t OldThreadWaitMode;
  2735. int8_t OldThreadState;
  2736. int8_t OldThreadWaitIdealProcessor;
  2737. uint32_t NewThreadWaitTime;
  2738. uint32_t Reserved;
  2739. };
  2740. VOID WINAPI MicroProfileContextSwitchCallback(PEVENT_TRACE pEvent)
  2741. {
  2742. if (pEvent->Header.Guid == g_MicroProfileThreadClassGuid)
  2743. {
  2744. if (pEvent->Header.Class.Type == 36)
  2745. {
  2746. MicroProfileSCSwitch* pCSwitch = (MicroProfileSCSwitch*) pEvent->MofData;
  2747. if ((pCSwitch->NewThreadId != 0) || (pCSwitch->OldThreadId != 0))
  2748. {
  2749. MicroProfileContextSwitch Switch;
  2750. Switch.nThreadOut = pCSwitch->OldThreadId;
  2751. Switch.nThreadIn = pCSwitch->NewThreadId;
  2752. Switch.nCpu = pEvent->BufferContext.ProcessorNumber;
  2753. Switch.nTicks = pEvent->Header.TimeStamp.QuadPart;
  2754. MicroProfileContextSwitchPut(&Switch);
  2755. }
  2756. }
  2757. }
  2758. }
  2759. ULONG WINAPI MicroProfileBufferCallback(PEVENT_TRACE_LOGFILE Buffer)
  2760. {
  2761. return (S.bContextSwitchStop || !S.bContextSwitchRunning) ? FALSE : TRUE;
  2762. }
  2763. struct MicroProfileKernelTraceProperties : public EVENT_TRACE_PROPERTIES
  2764. {
  2765. char dummy[sizeof(KERNEL_LOGGER_NAME)];
  2766. };
  2767. void MicroProfileContextSwitchShutdownTrace()
  2768. {
  2769. TRACEHANDLE SessionHandle = 0;
  2770. MicroProfileKernelTraceProperties sessionProperties;
  2771. ZeroMemory(&sessionProperties, sizeof(sessionProperties));
  2772. sessionProperties.Wnode.BufferSize = sizeof(sessionProperties);
  2773. sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
  2774. sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution
  2775. sessionProperties.Wnode.Guid = SystemTraceControlGuid;
  2776. sessionProperties.BufferSize = 1;
  2777. sessionProperties.NumberOfBuffers = 128;
  2778. sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH;
  2779. sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  2780. sessionProperties.MaximumFileSize = 0;
  2781. sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
  2782. sessionProperties.LogFileNameOffset = 0;
  2783. EVENT_TRACE_LOGFILE log;
  2784. ZeroMemory(&log, sizeof(log));
  2785. log.LoggerName = KERNEL_LOGGER_NAME;
  2786. log.ProcessTraceMode = 0;
  2787. TRACEHANDLE hLog = OpenTrace(&log);
  2788. if (hLog)
  2789. {
  2790. ControlTrace(SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties, EVENT_TRACE_CONTROL_STOP);
  2791. }
  2792. CloseTrace(hLog);
  2793. }
  2794. void* MicroProfileTraceThread(void* unused)
  2795. {
  2796. MicroProfileContextSwitchShutdownTrace();
  2797. ULONG status = ERROR_SUCCESS;
  2798. TRACEHANDLE SessionHandle = 0;
  2799. MicroProfileKernelTraceProperties sessionProperties;
  2800. ZeroMemory(&sessionProperties, sizeof(sessionProperties));
  2801. sessionProperties.Wnode.BufferSize = sizeof(sessionProperties);
  2802. sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
  2803. sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution
  2804. sessionProperties.Wnode.Guid = SystemTraceControlGuid;
  2805. sessionProperties.BufferSize = 1;
  2806. sessionProperties.NumberOfBuffers = 128;
  2807. sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH|EVENT_TRACE_FLAG_PROCESS;
  2808. sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  2809. sessionProperties.MaximumFileSize = 0;
  2810. sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
  2811. sessionProperties.LogFileNameOffset = 0;
  2812. status = StartTrace((PTRACEHANDLE) &SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties);
  2813. if (ERROR_SUCCESS != status)
  2814. {
  2815. S.bContextSwitchRunning = false;
  2816. return 0;
  2817. }
  2818. EVENT_TRACE_LOGFILE log;
  2819. ZeroMemory(&log, sizeof(log));
  2820. log.LoggerName = KERNEL_LOGGER_NAME;
  2821. log.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_RAW_TIMESTAMP;
  2822. log.EventCallback = MicroProfileContextSwitchCallback;
  2823. log.BufferCallback = MicroProfileBufferCallback;
  2824. TRACEHANDLE hLog = OpenTrace(&log);
  2825. ProcessTrace(&hLog, 1, 0, 0);
  2826. CloseTrace(hLog);
  2827. MicroProfileContextSwitchShutdownTrace();
  2828. S.bContextSwitchRunning = false;
  2829. return 0;
  2830. }
  2831. bool MicroProfileIsLocalThread(uint32_t nThreadId)
  2832. {
  2833. HANDLE h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, nThreadId);
  2834. if(h == NULL)
  2835. return false;
  2836. DWORD hProcess = GetProcessIdOfThread(h);
  2837. CloseHandle(h);
  2838. return GetCurrentProcessId() == hProcess;
  2839. }
  2840. #elif defined(__APPLE__)
  2841. #include <sys/time.h>
  2842. void* MicroProfileTraceThread(void* unused)
  2843. {
  2844. FILE* pFile = fopen("mypipe", "r");
  2845. if(!pFile)
  2846. {
  2847. printf("CONTEXT SWITCH FAILED TO OPEN FILE: make sure to run dtrace script\n");
  2848. S.bContextSwitchRunning = false;
  2849. return 0;
  2850. }
  2851. printf("STARTING TRACE THREAD\n");
  2852. char* pLine = 0;
  2853. size_t cap = 0;
  2854. size_t len = 0;
  2855. struct timeval tv;
  2856. gettimeofday(&tv, NULL);
  2857. uint64_t nsSinceEpoch = ((uint64_t)(tv.tv_sec) * 1000000 + (uint64_t)(tv.tv_usec)) * 1000;
  2858. uint64_t nTickEpoch = MP_TICK();
  2859. uint32_t nLastThread[MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS] = {0};
  2860. mach_timebase_info_data_t sTimebaseInfo;
  2861. mach_timebase_info(&sTimebaseInfo);
  2862. S.bContextSwitchRunning = true;
  2863. uint64_t nProcessed = 0;
  2864. uint64_t nProcessedLast = 0;
  2865. while((len = getline(&pLine, &cap, pFile))>0 && !S.bContextSwitchStop)
  2866. {
  2867. nProcessed += len;
  2868. if(nProcessed - nProcessedLast > 10<<10)
  2869. {
  2870. nProcessedLast = nProcessed;
  2871. printf("processed %llukb %llukb\n", (nProcessed-nProcessedLast)>>10,nProcessed >>10);
  2872. }
  2873. char* pX = strchr(pLine, 'X');
  2874. if(pX)
  2875. {
  2876. int cpu = atoi(pX+1);
  2877. char* pX2 = strchr(pX + 1, 'X');
  2878. char* pX3 = strchr(pX2 + 1, 'X');
  2879. int thread = atoi(pX2+1);
  2880. char* lala;
  2881. int64_t timestamp = strtoll(pX3 + 1, &lala, 10);
  2882. MicroProfileContextSwitch Switch;
  2883. //convert to ticks.
  2884. uint64_t nDeltaNsSinceEpoch = timestamp - nsSinceEpoch;
  2885. uint64_t nDeltaTickSinceEpoch = sTimebaseInfo.numer * nDeltaNsSinceEpoch / sTimebaseInfo.denom;
  2886. uint64_t nTicks = nDeltaTickSinceEpoch + nTickEpoch;
  2887. if(cpu < MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS)
  2888. {
  2889. Switch.nThreadOut = nLastThread[cpu];
  2890. Switch.nThreadIn = thread;
  2891. nLastThread[cpu] = thread;
  2892. Switch.nCpu = cpu;
  2893. Switch.nTicks = nTicks;
  2894. MicroProfileContextSwitchPut(&Switch);
  2895. }
  2896. }
  2897. }
  2898. printf("EXITING TRACE THREAD\n");
  2899. S.bContextSwitchRunning = false;
  2900. return 0;
  2901. }
  2902. bool MicroProfileIsLocalThread(uint32_t nThreadId)
  2903. {
  2904. return false;
  2905. }
  2906. #endif
  2907. #else
  2908. bool MicroProfileIsLocalThread([[maybe_unused]] uint32_t nThreadId) { return false; }
  2909. void MicroProfileStopContextSwitchTrace(){}
  2910. void MicroProfileStartContextSwitchTrace(){}
  2911. #endif
  2912. #if MICROPROFILE_GPU_TIMERS_D3D11
  2913. uint32_t MicroProfileGpuInsertTimeStamp()
  2914. {
  2915. MicroProfileD3D11Frame& Frame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame];
  2916. if(Frame.m_nRateQueryStarted)
  2917. {
  2918. uint32_t nCurrent = (Frame.m_nQueryStart + Frame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES;
  2919. uint32_t nNext = (nCurrent + 1) % MICROPROFILE_D3D_MAX_QUERIES;
  2920. if(nNext != S.GPU.m_nQueryGet)
  2921. {
  2922. Frame.m_nQueryCount++;
  2923. ID3D11Query* pQuery = (ID3D11Query*)S.GPU.m_pQueries[nCurrent];
  2924. ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext;
  2925. pContext->End(pQuery);
  2926. S.GPU.m_nQueryPut = nNext;
  2927. return nCurrent;
  2928. }
  2929. }
  2930. return (uint32_t)-1;
  2931. }
  2932. uint64_t MicroProfileGpuGetTimeStamp(uint32_t nIndex)
  2933. {
  2934. if(nIndex == (uint32_t)-1)
  2935. {
  2936. return (uint64_t)-1;
  2937. }
  2938. int64_t nResult = S.GPU.m_nQueryResults[nIndex];
  2939. MP_ASSERT(nResult != -1);
  2940. return nResult;
  2941. }
  2942. bool MicroProfileGpuGetData(void* pQuery, void* pData, uint32_t nDataSize)
  2943. {
  2944. HRESULT hr;
  2945. do
  2946. {
  2947. hr = ((ID3D11DeviceContext*)S.GPU.m_pDeviceContext)->GetData((ID3D11Query*)pQuery, pData, nDataSize, 0);
  2948. }while(hr == S_FALSE);
  2949. switch(hr)
  2950. {
  2951. case DXGI_ERROR_DEVICE_REMOVED:
  2952. case DXGI_ERROR_INVALID_CALL:
  2953. case E_INVALIDARG:
  2954. MP_BREAK();
  2955. return false;
  2956. }
  2957. return true;
  2958. }
  2959. uint64_t MicroProfileTicksPerSecondGpu()
  2960. {
  2961. return S.GPU.m_nQueryFrequency;
  2962. }
  2963. void MicroProfileGpuFlip()
  2964. {
  2965. MicroProfileD3D11Frame& CurrentFrame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame];
  2966. ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext;
  2967. if(CurrentFrame.m_nRateQueryStarted)
  2968. {
  2969. pContext->End((ID3D11Query*)CurrentFrame.m_pRateQuery);
  2970. }
  2971. uint32_t nNextFrame = (S.GPU.m_nQueryFrame + 1) % MICROPROFILE_GPU_FRAME_DELAY;
  2972. MicroProfileD3D11Frame& OldFrame = S.GPU.m_QueryFrames[nNextFrame];
  2973. if(OldFrame.m_nRateQueryStarted)
  2974. {
  2975. struct RateQueryResult
  2976. {
  2977. uint64_t nFrequency;
  2978. BOOL bDisjoint;
  2979. };
  2980. RateQueryResult Result;
  2981. if(MicroProfileGpuGetData(OldFrame.m_pRateQuery, &Result, sizeof(Result)))
  2982. {
  2983. if(S.GPU.m_nQueryFrequency != (int64_t)Result.nFrequency)
  2984. {
  2985. if(S.GPU.m_nQueryFrequency)
  2986. {
  2987. OutputDebugString("Query freq changing");
  2988. }
  2989. S.GPU.m_nQueryFrequency = Result.nFrequency;
  2990. }
  2991. uint32_t nStart = OldFrame.m_nQueryStart;
  2992. uint32_t nCount = OldFrame.m_nQueryCount;
  2993. for(uint32_t i = 0; i < nCount; ++i)
  2994. {
  2995. uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES;
  2996. if(!MicroProfileGpuGetData(S.GPU.m_pQueries[nIndex], &S.GPU.m_nQueryResults[nIndex], sizeof(uint64_t)))
  2997. {
  2998. S.GPU.m_nQueryResults[nIndex] = -1;
  2999. }
  3000. }
  3001. }
  3002. else
  3003. {
  3004. uint32_t nStart = OldFrame.m_nQueryStart;
  3005. uint32_t nCount = OldFrame.m_nQueryCount;
  3006. for(uint32_t i = 0; i < nCount; ++i)
  3007. {
  3008. uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES;
  3009. S.GPU.m_nQueryResults[nIndex] = -1;
  3010. }
  3011. }
  3012. S.GPU.m_nQueryGet = (OldFrame.m_nQueryStart + OldFrame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES;
  3013. }
  3014. S.GPU.m_nQueryFrame = nNextFrame;
  3015. MicroProfileD3D11Frame& NextFrame = S.GPU.m_QueryFrames[nNextFrame];
  3016. pContext->Begin((ID3D11Query*)NextFrame.m_pRateQuery);
  3017. NextFrame.m_nQueryStart = S.GPU.m_nQueryPut;
  3018. NextFrame.m_nQueryCount = 0;
  3019. NextFrame.m_nRateQueryStarted = 1;
  3020. }
  3021. void MicroProfileGpuInitD3D11(void* pDevice_, void* pDeviceContext_)
  3022. {
  3023. ID3D11Device* pDevice = (ID3D11Device*)pDevice_;
  3024. ID3D11DeviceContext* pDeviceContext = (ID3D11DeviceContext*)pDeviceContext_;
  3025. S.GPU.m_pDeviceContext = pDeviceContext_;
  3026. D3D11_QUERY_DESC Desc;
  3027. Desc.MiscFlags = 0;
  3028. Desc.Query = D3D11_QUERY_TIMESTAMP;
  3029. for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i)
  3030. {
  3031. HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_pQueries[i]);
  3032. MP_ASSERT(hr == S_OK);
  3033. S.GPU.m_nQueryResults[i] = -1;
  3034. }
  3035. S.GPU.m_nQueryPut = 0;
  3036. S.GPU.m_nQueryGet = 0;
  3037. S.GPU.m_nQueryFrame = 0;
  3038. S.GPU.m_nQueryFrequency = 0;
  3039. Desc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
  3040. for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i)
  3041. {
  3042. S.GPU.m_QueryFrames[i].m_nQueryStart = 0;
  3043. S.GPU.m_QueryFrames[i].m_nQueryCount = 0;
  3044. S.GPU.m_QueryFrames[i].m_nRateQueryStarted = 0;
  3045. HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_QueryFrames[i].m_pRateQuery);
  3046. MP_ASSERT(hr == S_OK);
  3047. }
  3048. }
  3049. void MicroProfileGpuShutdown()
  3050. {
  3051. for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i)
  3052. {
  3053. ((ID3D11Query*)&S.GPU.m_pQueries[i])->Release();
  3054. S.GPU.m_pQueries[i] = 0;
  3055. }
  3056. for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i)
  3057. {
  3058. ((ID3D11Query*)S.GPU.m_QueryFrames[i].m_pRateQuery)->Release();
  3059. S.GPU.m_QueryFrames[i].m_pRateQuery = 0;
  3060. }
  3061. }
  3062. int MicroProfileGetGpuTickReference(int64_t* pOutCPU, int64_t* pOutGpu)
  3063. {
  3064. return 0;
  3065. }
  3066. #elif MICROPROFILE_GPU_TIMERS_GL
  3067. void MicroProfileGpuInitGL()
  3068. {
  3069. S.GPU.GLTimerPos = 0;
  3070. glGenQueries(MICROPROFILE_GL_MAX_QUERIES, &S.GPU.GLTimers[0]);
  3071. }
  3072. uint32_t MicroProfileGpuInsertTimeStamp()
  3073. {
  3074. uint32_t nIndex = (S.GPU.GLTimerPos+1)%MICROPROFILE_GL_MAX_QUERIES;
  3075. glQueryCounter(S.GPU.GLTimers[nIndex], GL_TIMESTAMP);
  3076. S.GPU.GLTimerPos = nIndex;
  3077. return nIndex;
  3078. }
  3079. uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey)
  3080. {
  3081. uint64_t result;
  3082. glGetQueryObjectui64v(S.GPU.GLTimers[nKey], GL_QUERY_RESULT, &result);
  3083. return result;
  3084. }
  3085. uint64_t MicroProfileTicksPerSecondGpu()
  3086. {
  3087. return 1000000000ll;
  3088. }
  3089. int MicroProfileGetGpuTickReference(int64_t* pOutCpu, int64_t* pOutGpu)
  3090. {
  3091. int64_t nGpuTimeStamp;
  3092. glGetInteger64v(GL_TIMESTAMP, &nGpuTimeStamp);
  3093. if(nGpuTimeStamp)
  3094. {
  3095. *pOutCpu = MP_TICK();
  3096. *pOutGpu = nGpuTimeStamp;
  3097. #if 0 //debug test if timestamp diverges
  3098. static int64_t nTicksPerSecondCpu = MicroProfileTicksPerSecondCpu();
  3099. static int64_t nTicksPerSecondGpu = MicroProfileTicksPerSecondGpu();
  3100. static int64_t nGpuStart = 0;
  3101. static int64_t nCpuStart = 0;
  3102. if(!nCpuStart)
  3103. {
  3104. nCpuStart = *pOutCpu;
  3105. nGpuStart = *pOutGpu;
  3106. }
  3107. static int nCountDown = 100;
  3108. if(0 == nCountDown--)
  3109. {
  3110. int64_t nCurCpu = *pOutCpu;
  3111. int64_t nCurGpu = *pOutGpu;
  3112. double fDistanceCpu = (nCurCpu - nCpuStart) / (double)nTicksPerSecondCpu;
  3113. double fDistanceGpu = (nCurGpu - nGpuStart) / (double)nTicksPerSecondGpu;
  3114. char buf[254];
  3115. snprintf(buf, sizeof(buf)-1,"Distance %f %f diff %f\n", fDistanceCpu, fDistanceGpu, fDistanceCpu-fDistanceGpu);
  3116. OutputDebugString(buf);
  3117. nCountDown = 100;
  3118. }
  3119. #endif
  3120. return 1;
  3121. }
  3122. return 0;
  3123. }
  3124. #endif
  3125. #undef S
  3126. #ifdef _MSC_VER
  3127. #pragma warning(pop)
  3128. #endif
  3129. #endif
  3130. #endif
  3131. #ifdef MICROPROFILE_EMBED_HTML
  3132. #include "microprofile_html.h"
  3133. #endif