microprofile.h 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591
  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. #pragma warning(push)
  751. #pragma warning(disable: 4244)
  752. int64_t MicroProfileTicksPerSecondCpu()
  753. {
  754. static int64_t nTicksPerSecond = 0;
  755. if(nTicksPerSecond == 0)
  756. {
  757. QueryPerformanceFrequency((LARGE_INTEGER*)&nTicksPerSecond);
  758. }
  759. return nTicksPerSecond;
  760. }
  761. int64_t MicroProfileGetTick()
  762. {
  763. int64_t ticks;
  764. QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
  765. return ticks;
  766. }
  767. #endif
  768. #if defined(MICROPROFILE_WEBSERVER) || defined(MICROPROFILE_CONTEXT_SWITCH_TRACE)
  769. typedef void* (*MicroProfileThreadFunc)(void*);
  770. #ifndef _WIN32
  771. typedef pthread_t MicroProfileThread;
  772. inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func)
  773. {
  774. pthread_attr_t Attr;
  775. int r = pthread_attr_init(&Attr);
  776. MP_ASSERT(r == 0);
  777. pthread_create(pThread, &Attr, Func, 0);
  778. }
  779. inline void MicroProfileThreadJoin(MicroProfileThread* pThread)
  780. {
  781. int r = pthread_join(*pThread, 0);
  782. MP_ASSERT(r == 0);
  783. }
  784. #elif defined(_MSC_VER)
  785. typedef HANDLE MicroProfileThread;
  786. DWORD _stdcall ThreadTrampoline(void* pFunc)
  787. {
  788. MicroProfileThreadFunc F = (MicroProfileThreadFunc)pFunc;
  789. return (uint32_t)F(0);
  790. }
  791. inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func)
  792. {
  793. *pThread = CreateThread(0, 0, ThreadTrampoline, Func, 0, 0);
  794. }
  795. inline void MicroProfileThreadJoin(MicroProfileThread* pThread)
  796. {
  797. WaitForSingleObject(*pThread, INFINITE);
  798. CloseHandle(*pThread);
  799. }
  800. #else
  801. #include <thread>
  802. typedef std::thread* MicroProfileThread;
  803. inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func)
  804. {
  805. *pThread = new std::thread(Func, nullptr);
  806. }
  807. inline void MicroProfileThreadJoin(MicroProfileThread* pThread)
  808. {
  809. (*pThread)->join();
  810. delete *pThread;
  811. }
  812. #endif
  813. #endif
  814. #if MICROPROFILE_WEBSERVER
  815. #ifdef _WIN32
  816. #define MP_INVALID_SOCKET(f) (f == INVALID_SOCKET)
  817. #endif
  818. #ifndef _WIN32
  819. #include <sys/socket.h>
  820. #include <netinet/in.h>
  821. #include <fcntl.h>
  822. #define MP_INVALID_SOCKET(f) (f < 0)
  823. #endif
  824. void MicroProfileWebServerStart();
  825. void MicroProfileWebServerStop();
  826. bool MicroProfileWebServerUpdate();
  827. void MicroProfileDumpToFile();
  828. #else
  829. #define MicroProfileWebServerStart() do{}while(0)
  830. #define MicroProfileWebServerStop() do{}while(0)
  831. #define MicroProfileWebServerUpdate() false
  832. #define MicroProfileDumpToFile() do{} while(0)
  833. #endif
  834. #if MICROPROFILE_GPU_TIMERS_D3D11
  835. void MicroProfileGpuFlip();
  836. void MicroProfileGpuShutdown();
  837. #else
  838. #define MicroProfileGpuFlip() do{}while(0)
  839. #define MicroProfileGpuShutdown() do{}while(0)
  840. #endif
  841. #include <stdlib.h>
  842. #include <stdio.h>
  843. #include <math.h>
  844. #include <algorithm>
  845. #ifndef MICROPROFILE_DEBUG
  846. #define MICROPROFILE_DEBUG 0
  847. #endif
  848. #define S g_MicroProfile
  849. MicroProfile g_MicroProfile;
  850. MicroProfileThreadLog* g_MicroProfileGpuLog = 0;
  851. #ifdef MICROPROFILE_IOS
  852. // iOS doesn't support __thread
  853. static pthread_key_t g_MicroProfileThreadLogKey;
  854. static pthread_once_t g_MicroProfileThreadLogKeyOnce = PTHREAD_ONCE_INIT;
  855. static void MicroProfileCreateThreadLogKey()
  856. {
  857. pthread_key_create(&g_MicroProfileThreadLogKey, NULL);
  858. }
  859. #else
  860. MP_THREAD_LOCAL MicroProfileThreadLog* g_MicroProfileThreadLog = 0;
  861. #endif
  862. 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)
  863. MICROPROFILE_DEFINE(g_MicroProfileFlip, "MicroProfile", "MicroProfileFlip", 0x3355ee);
  864. MICROPROFILE_DEFINE(g_MicroProfileThreadLoop, "MicroProfile", "ThreadLoop", 0x3355ee);
  865. MICROPROFILE_DEFINE(g_MicroProfileClear, "MicroProfile", "Clear", 0x3355ee);
  866. MICROPROFILE_DEFINE(g_MicroProfileAccumulate, "MicroProfile", "Accumulate", 0x3355ee);
  867. MICROPROFILE_DEFINE(g_MicroProfileContextSwitchSearch,"MicroProfile", "ContextSwitchSearch", 0xDD7300);
  868. inline std::recursive_mutex& MicroProfileMutex()
  869. {
  870. static std::recursive_mutex Mutex;
  871. return Mutex;
  872. }
  873. std::recursive_mutex& MicroProfileGetMutex()
  874. {
  875. return MicroProfileMutex();
  876. }
  877. MICROPROFILE_API MicroProfile* MicroProfileGet()
  878. {
  879. return &g_MicroProfile;
  880. }
  881. MicroProfileThreadLog* MicroProfileCreateThreadLog(const char* pName);
  882. void MicroProfileInit()
  883. {
  884. std::recursive_mutex& mutex = MicroProfileMutex();
  885. bool bUseLock = g_bUseLock;
  886. if(bUseLock)
  887. mutex.lock();
  888. static bool bOnce = true;
  889. if(bOnce)
  890. {
  891. S.nMemUsage += sizeof(S);
  892. bOnce = false;
  893. memset(&S, 0, sizeof(S));
  894. for(int i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  895. {
  896. S.GroupInfo[i].pName[0] = '\0';
  897. }
  898. for(int i = 0; i < MICROPROFILE_MAX_CATEGORIES; ++i)
  899. {
  900. S.CategoryInfo[i].pName[0] = '\0';
  901. S.CategoryInfo[i].nGroupMask = 0;
  902. }
  903. strcpy(&S.CategoryInfo[0].pName[0], "default");
  904. S.nCategoryCount = 1;
  905. for(int i = 0; i < MICROPROFILE_MAX_TIMERS; ++i)
  906. {
  907. S.TimerInfo[i].pName[0] = '\0';
  908. }
  909. S.nGroupCount = 0;
  910. S.nAggregateFlipTick = MP_TICK();
  911. S.nActiveGroup = 0;
  912. S.nActiveBars = 0;
  913. S.nForceGroup = 0;
  914. S.nAllGroupsWanted = 0;
  915. S.nActiveGroupWanted = 0;
  916. S.nAllThreadsWanted = 1;
  917. S.nAggregateFlip = 0;
  918. S.nTotalTimers = 0;
  919. for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i)
  920. {
  921. S.Graph[i].nToken = MICROPROFILE_INVALID_TOKEN;
  922. }
  923. S.nRunning = 1;
  924. S.fReferenceTime = 33.33f;
  925. S.fRcpReferenceTime = 1.f / S.fReferenceTime;
  926. S.nFreeListHead = -1;
  927. int64_t nTick = MP_TICK();
  928. for(int i = 0; i < MICROPROFILE_MAX_FRAME_HISTORY; ++i)
  929. {
  930. S.Frames[i].nFrameStartCpu = nTick;
  931. S.Frames[i].nFrameStartGpu = -1;
  932. }
  933. MicroProfileThreadLog* pGpu = MicroProfileCreateThreadLog("GPU");
  934. g_MicroProfileGpuLog = pGpu;
  935. MP_ASSERT(S.Pool[0] == pGpu);
  936. pGpu->nGpu = 1;
  937. pGpu->nThreadId = 0;
  938. S.nWebServerDataSent = (uint64_t)-1;
  939. }
  940. if(bUseLock)
  941. mutex.unlock();
  942. }
  943. void MicroProfileShutdown()
  944. {
  945. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  946. MicroProfileWebServerStop();
  947. MicroProfileStopContextSwitchTrace();
  948. MicroProfileGpuShutdown();
  949. }
  950. #ifdef MICROPROFILE_IOS
  951. inline MicroProfileThreadLog* MicroProfileGetThreadLog()
  952. {
  953. pthread_once(&g_MicroProfileThreadLogKeyOnce, MicroProfileCreateThreadLogKey);
  954. return (MicroProfileThreadLog*)pthread_getspecific(g_MicroProfileThreadLogKey);
  955. }
  956. inline void MicroProfileSetThreadLog(MicroProfileThreadLog* pLog)
  957. {
  958. pthread_once(&g_MicroProfileThreadLogKeyOnce, MicroProfileCreateThreadLogKey);
  959. pthread_setspecific(g_MicroProfileThreadLogKey, pLog);
  960. }
  961. #else
  962. inline MicroProfileThreadLog* MicroProfileGetThreadLog()
  963. {
  964. return g_MicroProfileThreadLog;
  965. }
  966. inline void MicroProfileSetThreadLog(MicroProfileThreadLog* pLog)
  967. {
  968. g_MicroProfileThreadLog = pLog;
  969. }
  970. #endif
  971. MicroProfileThreadLog* MicroProfileCreateThreadLog(const char* pName)
  972. {
  973. MicroProfileThreadLog* pLog = 0;
  974. if(S.nFreeListHead != -1)
  975. {
  976. pLog = S.Pool[S.nFreeListHead];
  977. MP_ASSERT(pLog->nPut.load() == 0);
  978. MP_ASSERT(pLog->nGet.load() == 0);
  979. S.nFreeListHead = S.Pool[S.nFreeListHead]->nFreeListNext;
  980. pLog->Reset();
  981. }
  982. else
  983. {
  984. pLog = new MicroProfileThreadLog;
  985. S.nMemUsage += sizeof(MicroProfileThreadLog);
  986. S.Pool[S.nNumLogs++] = pLog;
  987. }
  988. int len = (int)strlen(pName);
  989. int maxlen = sizeof(pLog->ThreadName)-1;
  990. len = len < maxlen ? len : maxlen;
  991. memcpy(&pLog->ThreadName[0], pName, len);
  992. pLog->ThreadName[len] = '\0';
  993. pLog->nThreadId = MP_GETCURRENTTHREADID();
  994. pLog->nFreeListNext = -1;
  995. pLog->nActive = 1;
  996. return pLog;
  997. }
  998. void MicroProfileOnThreadCreate(const char* pThreadName)
  999. {
  1000. g_bUseLock = true;
  1001. MicroProfileInit();
  1002. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1003. MP_ASSERT(MicroProfileGetThreadLog() == 0);
  1004. MicroProfileThreadLog* pLog = MicroProfileCreateThreadLog(pThreadName ? pThreadName : MicroProfileGetThreadName());
  1005. MP_ASSERT(pLog);
  1006. MicroProfileSetThreadLog(pLog);
  1007. }
  1008. void MicroProfileOnThreadExit()
  1009. {
  1010. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1011. MicroProfileThreadLog* pLog = MicroProfileGetThreadLog();
  1012. if(pLog)
  1013. {
  1014. int32_t nLogIndex = -1;
  1015. for(int i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1016. {
  1017. if(pLog == S.Pool[i])
  1018. {
  1019. nLogIndex = i;
  1020. break;
  1021. }
  1022. }
  1023. MP_ASSERT(nLogIndex < MICROPROFILE_MAX_THREADS && nLogIndex > 0);
  1024. pLog->nFreeListNext = S.nFreeListHead;
  1025. pLog->nActive = 0;
  1026. pLog->nPut.store(0);
  1027. pLog->nGet.store(0);
  1028. S.nFreeListHead = nLogIndex;
  1029. for(int i = 0; i < MICROPROFILE_MAX_FRAME_HISTORY; ++i)
  1030. {
  1031. S.Frames[i].nLogStart[nLogIndex] = 0;
  1032. }
  1033. pLog->nGroupStackPos.fill(0);
  1034. pLog->nGroupTicks.fill(0);
  1035. }
  1036. }
  1037. void MicroProfileInitThreadLog()
  1038. {
  1039. MicroProfileOnThreadCreate(nullptr);
  1040. }
  1041. struct MicroProfileScopeLock
  1042. {
  1043. bool bUseLock;
  1044. std::recursive_mutex& m;
  1045. MicroProfileScopeLock(std::recursive_mutex& m) : bUseLock(g_bUseLock), m(m)
  1046. {
  1047. if(bUseLock)
  1048. m.lock();
  1049. }
  1050. ~MicroProfileScopeLock()
  1051. {
  1052. if(bUseLock)
  1053. m.unlock();
  1054. }
  1055. };
  1056. MicroProfileToken MicroProfileFindToken(const char* pGroup, const char* pName)
  1057. {
  1058. MicroProfileInit();
  1059. MicroProfileScopeLock L(MicroProfileMutex());
  1060. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1061. {
  1062. if(!MP_STRCASECMP(pName, S.TimerInfo[i].pName) && !MP_STRCASECMP(pGroup, S.GroupInfo[S.TimerToGroup[i]].pName))
  1063. {
  1064. return S.TimerInfo[i].nToken;
  1065. }
  1066. }
  1067. return MICROPROFILE_INVALID_TOKEN;
  1068. }
  1069. inline uint16_t MicroProfileGetGroup(const char* pGroup, MicroProfileTokenType Type)
  1070. {
  1071. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  1072. {
  1073. if(!MP_STRCASECMP(pGroup, S.GroupInfo[i].pName))
  1074. {
  1075. return i;
  1076. }
  1077. }
  1078. uint16_t nGroupIndex = 0xffff;
  1079. uint32_t nLen = (uint32_t)strlen(pGroup);
  1080. if(nLen > MICROPROFILE_NAME_MAX_LEN-1)
  1081. nLen = MICROPROFILE_NAME_MAX_LEN-1;
  1082. memcpy(&S.GroupInfo[S.nGroupCount].pName[0], pGroup, nLen);
  1083. S.GroupInfo[S.nGroupCount].pName[nLen] = '\0';
  1084. S.GroupInfo[S.nGroupCount].nNameLen = nLen;
  1085. S.GroupInfo[S.nGroupCount].nNumTimers = 0;
  1086. S.GroupInfo[S.nGroupCount].nGroupIndex = S.nGroupCount;
  1087. S.GroupInfo[S.nGroupCount].Type = Type;
  1088. S.GroupInfo[S.nGroupCount].nMaxTimerNameLen = 0;
  1089. S.GroupInfo[S.nGroupCount].nColor = 0x88888888;
  1090. S.GroupInfo[S.nGroupCount].nCategory = 0;
  1091. S.CategoryInfo[0].nGroupMask |= (1ll << (uint64_t)S.nGroupCount);
  1092. nGroupIndex = S.nGroupCount++;
  1093. S.nGroupMask = (S.nGroupMask<<1)|1;
  1094. MP_ASSERT(nGroupIndex < MICROPROFILE_MAX_GROUPS);
  1095. return nGroupIndex;
  1096. }
  1097. inline void MicroProfileRegisterGroup(const char* pGroup, const char* pCategory, uint32_t nColor)
  1098. {
  1099. int nCategoryIndex = -1;
  1100. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1101. {
  1102. if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName))
  1103. {
  1104. nCategoryIndex = (int)i;
  1105. break;
  1106. }
  1107. }
  1108. if(-1 == nCategoryIndex && S.nCategoryCount < MICROPROFILE_MAX_CATEGORIES)
  1109. {
  1110. MP_ASSERT(S.CategoryInfo[S.nCategoryCount].pName[0] == '\0');
  1111. nCategoryIndex = (int)S.nCategoryCount++;
  1112. uint32_t nLen = (uint32_t)strlen(pCategory);
  1113. if(nLen > MICROPROFILE_NAME_MAX_LEN-1)
  1114. nLen = MICROPROFILE_NAME_MAX_LEN-1;
  1115. memcpy(&S.CategoryInfo[nCategoryIndex].pName[0], pCategory, nLen);
  1116. S.CategoryInfo[nCategoryIndex].pName[nLen] = '\0';
  1117. }
  1118. uint16_t nGroup = MicroProfileGetGroup(pGroup, 0 != MP_STRCASECMP(pGroup, "gpu")?MicroProfileTokenTypeCpu : MicroProfileTokenTypeGpu);
  1119. S.GroupInfo[nGroup].nColor = nColor;
  1120. if(nCategoryIndex >= 0)
  1121. {
  1122. uint64_t nBit = 1ll << nGroup;
  1123. uint32_t nOldCategory = S.GroupInfo[nGroup].nCategory;
  1124. S.CategoryInfo[nOldCategory].nGroupMask &= ~nBit;
  1125. S.CategoryInfo[nCategoryIndex].nGroupMask |= nBit;
  1126. S.GroupInfo[nGroup].nCategory = nCategoryIndex;
  1127. }
  1128. }
  1129. MicroProfileToken MicroProfileGetToken(const char* pGroup, const char* pName, uint32_t nColor, MicroProfileTokenType Type)
  1130. {
  1131. MicroProfileInit();
  1132. MicroProfileScopeLock L(MicroProfileMutex());
  1133. MicroProfileToken ret = MicroProfileFindToken(pGroup, pName);
  1134. if(ret != MICROPROFILE_INVALID_TOKEN)
  1135. return ret;
  1136. uint16_t nGroupIndex = MicroProfileGetGroup(pGroup, Type);
  1137. uint16_t nTimerIndex = (uint16_t)(S.nTotalTimers++);
  1138. uint64_t nGroupMask = 1ll << nGroupIndex;
  1139. MicroProfileToken nToken = MicroProfileMakeToken(nGroupMask, nTimerIndex);
  1140. S.GroupInfo[nGroupIndex].nNumTimers++;
  1141. S.GroupInfo[nGroupIndex].nMaxTimerNameLen = MicroProfileMax(S.GroupInfo[nGroupIndex].nMaxTimerNameLen, (uint32_t)strlen(pName));
  1142. MP_ASSERT(S.GroupInfo[nGroupIndex].Type == Type); //dont mix cpu & gpu timers in the same group
  1143. S.nMaxGroupSize = MicroProfileMax(S.nMaxGroupSize, S.GroupInfo[nGroupIndex].nNumTimers);
  1144. S.TimerInfo[nTimerIndex].nToken = nToken;
  1145. uint32_t nLen = (uint32_t)strlen(pName);
  1146. if(nLen > MICROPROFILE_NAME_MAX_LEN-1)
  1147. nLen = MICROPROFILE_NAME_MAX_LEN-1;
  1148. memcpy(&S.TimerInfo[nTimerIndex].pName, pName, nLen);
  1149. S.TimerInfo[nTimerIndex].pName[nLen] = '\0';
  1150. S.TimerInfo[nTimerIndex].nNameLen = nLen;
  1151. S.TimerInfo[nTimerIndex].nColor = nColor&0xffffff;
  1152. S.TimerInfo[nTimerIndex].nGroupIndex = nGroupIndex;
  1153. S.TimerInfo[nTimerIndex].nTimerIndex = nTimerIndex;
  1154. S.TimerToGroup[nTimerIndex] = nGroupIndex;
  1155. return nToken;
  1156. }
  1157. MicroProfileToken MicroProfileGetMetaToken(const char* pName)
  1158. {
  1159. MicroProfileInit();
  1160. MicroProfileScopeLock L(MicroProfileMutex());
  1161. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1162. {
  1163. if(!S.MetaCounters[i].pName)
  1164. {
  1165. S.MetaCounters[i].pName = pName;
  1166. return i;
  1167. }
  1168. else if(!MP_STRCASECMP(pName, S.MetaCounters[i].pName))
  1169. {
  1170. return i;
  1171. }
  1172. }
  1173. MP_ASSERT(0);//out of slots, increase MICROPROFILE_META_MAX
  1174. return (MicroProfileToken)-1;
  1175. }
  1176. inline void MicroProfileLogPut(MicroProfileToken nToken_, uint64_t nTick, uint64_t nBegin, MicroProfileThreadLog* pLog)
  1177. {
  1178. MP_ASSERT(pLog != 0); //this assert is hit if MicroProfileOnCreateThread is not called
  1179. MP_ASSERT(pLog->nActive);
  1180. uint32_t nPos = pLog->nPut.load(std::memory_order_relaxed);
  1181. uint32_t nNextPos = (nPos+1) % MICROPROFILE_BUFFER_SIZE;
  1182. if(nNextPos == pLog->nGet.load(std::memory_order_relaxed))
  1183. {
  1184. S.nOverflow = 100;
  1185. }
  1186. else
  1187. {
  1188. pLog->Log[nPos] = MicroProfileMakeLogIndex(nBegin, nToken_, nTick);
  1189. pLog->nPut.store(nNextPos, std::memory_order_release);
  1190. }
  1191. }
  1192. uint64_t MicroProfileEnter(MicroProfileToken nToken_)
  1193. {
  1194. if(MicroProfileGetGroupMask(nToken_) & S.nActiveGroup)
  1195. {
  1196. if(!MicroProfileGetThreadLog())
  1197. {
  1198. MicroProfileInitThreadLog();
  1199. }
  1200. uint64_t nTick = MP_TICK();
  1201. MicroProfileLogPut(nToken_, nTick, MP_LOG_ENTER, MicroProfileGetThreadLog());
  1202. return nTick;
  1203. }
  1204. return MICROPROFILE_INVALID_TICK;
  1205. }
  1206. void MicroProfileMetaUpdate(MicroProfileToken nToken, int nCount, MicroProfileTokenType eTokenType)
  1207. {
  1208. if((MP_DRAW_META_FIRST<<nToken) & S.nActiveBars)
  1209. {
  1210. MicroProfileThreadLog* pLog = MicroProfileTokenTypeCpu == eTokenType ? MicroProfileGetThreadLog() : g_MicroProfileGpuLog;
  1211. if(pLog)
  1212. {
  1213. MP_ASSERT(nToken < MICROPROFILE_META_MAX);
  1214. MicroProfileLogPut(nToken, nCount, MP_LOG_META, pLog);
  1215. }
  1216. }
  1217. }
  1218. void MicroProfileLeave(MicroProfileToken nToken_, uint64_t nTickStart)
  1219. {
  1220. if(MICROPROFILE_INVALID_TICK != nTickStart)
  1221. {
  1222. if(!MicroProfileGetThreadLog())
  1223. {
  1224. MicroProfileInitThreadLog();
  1225. }
  1226. uint64_t nTick = MP_TICK();
  1227. MicroProfileThreadLog* pLog = MicroProfileGetThreadLog();
  1228. MicroProfileLogPut(nToken_, nTick, MP_LOG_LEAVE, pLog);
  1229. }
  1230. }
  1231. uint64_t MicroProfileGpuEnter(MicroProfileToken nToken_)
  1232. {
  1233. if(MicroProfileGetGroupMask(nToken_) & S.nActiveGroup)
  1234. {
  1235. uint64_t nTimer = MicroProfileGpuInsertTimeStamp();
  1236. MicroProfileLogPut(nToken_, nTimer, MP_LOG_ENTER, g_MicroProfileGpuLog);
  1237. MicroProfileLogPut(nToken_, MP_TICK(), MP_LOG_GPU_EXTRA, g_MicroProfileGpuLog);
  1238. return 1;
  1239. }
  1240. return 0;
  1241. }
  1242. void MicroProfileGpuLeave(MicroProfileToken nToken_, uint64_t nTickStart)
  1243. {
  1244. if(nTickStart)
  1245. {
  1246. uint64_t nTimer = MicroProfileGpuInsertTimeStamp();
  1247. MicroProfileLogPut(nToken_, nTimer, MP_LOG_LEAVE, g_MicroProfileGpuLog);
  1248. MicroProfileLogPut(nToken_, MP_TICK(), MP_LOG_GPU_EXTRA, g_MicroProfileGpuLog);
  1249. }
  1250. }
  1251. inline void MicroProfileContextSwitchPut(MicroProfileContextSwitch* pContextSwitch)
  1252. {
  1253. if(S.nRunning || pContextSwitch->nTicks <= S.nPauseTicks)
  1254. {
  1255. uint32_t nPut = S.nContextSwitchPut;
  1256. S.ContextSwitch[nPut] = *pContextSwitch;
  1257. S.nContextSwitchPut = (S.nContextSwitchPut+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1258. }
  1259. }
  1260. void MicroProfileGetRange(uint32_t nPut, uint32_t nGet, uint32_t nRange[2][2])
  1261. {
  1262. if(nPut > nGet)
  1263. {
  1264. nRange[0][0] = nGet;
  1265. nRange[0][1] = nPut;
  1266. nRange[1][0] = nRange[1][1] = 0;
  1267. }
  1268. else if(nPut != nGet)
  1269. {
  1270. MP_ASSERT(nGet != MICROPROFILE_BUFFER_SIZE);
  1271. uint32_t nCountEnd = MICROPROFILE_BUFFER_SIZE - nGet;
  1272. nRange[0][0] = nGet;
  1273. nRange[0][1] = nGet + nCountEnd;
  1274. nRange[1][0] = 0;
  1275. nRange[1][1] = nPut;
  1276. }
  1277. }
  1278. void MicroProfileFlip()
  1279. {
  1280. #if 0
  1281. //verify LogEntry wraps correctly
  1282. MicroProfileLogEntry c = MP_LOG_TICK_MASK-5000;
  1283. for(int i = 0; i < 10000; ++i, c += 1)
  1284. {
  1285. MicroProfileLogEntry l2 = (c+2500) & MP_LOG_TICK_MASK;
  1286. MP_ASSERT(2500 == MicroProfileLogTickDifference(c, l2));
  1287. }
  1288. #endif
  1289. MICROPROFILE_SCOPE(g_MicroProfileFlip);
  1290. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1291. MicroProfileGpuFlip();
  1292. if(S.nToggleRunning)
  1293. {
  1294. S.nRunning = !S.nRunning;
  1295. if(!S.nRunning)
  1296. S.nPauseTicks = MP_TICK();
  1297. S.nToggleRunning = 0;
  1298. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1299. {
  1300. MicroProfileThreadLog* pLog = S.Pool[i];
  1301. if(pLog)
  1302. {
  1303. pLog->nStackPos = 0;
  1304. }
  1305. }
  1306. }
  1307. uint32_t nAggregateClear = S.nAggregateClear || S.nAutoClearFrames, nAggregateFlip = 0;
  1308. if(S.nDumpFileNextFrame)
  1309. {
  1310. MicroProfileDumpToFile();
  1311. S.nDumpFileNextFrame = 0;
  1312. S.nAutoClearFrames = MICROPROFILE_GPU_FRAME_DELAY + 3; //hide spike from dumping webpage
  1313. }
  1314. if(S.nWebServerDataSent == (uint64_t)-1)
  1315. {
  1316. MicroProfileWebServerStart();
  1317. S.nWebServerDataSent = 0;
  1318. }
  1319. if(MicroProfileWebServerUpdate())
  1320. {
  1321. S.nAutoClearFrames = MICROPROFILE_GPU_FRAME_DELAY + 3; //hide spike from dumping webpage
  1322. }
  1323. if(S.nAutoClearFrames)
  1324. {
  1325. nAggregateClear = 1;
  1326. nAggregateFlip = 1;
  1327. S.nAutoClearFrames -= 1;
  1328. }
  1329. if(S.nRunning || S.nForceEnable)
  1330. {
  1331. S.nFramePutIndex++;
  1332. S.nFramePut = (S.nFramePut+1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1333. MP_ASSERT((S.nFramePutIndex % MICROPROFILE_MAX_FRAME_HISTORY) == S.nFramePut);
  1334. S.nFrameCurrent = (S.nFramePut + MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1335. S.nFrameCurrentIndex++;
  1336. uint32_t nFrameNext = (S.nFrameCurrent+1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1337. uint32_t nContextSwitchPut = S.nContextSwitchPut;
  1338. if(S.nContextSwitchLastPut < nContextSwitchPut)
  1339. {
  1340. S.nContextSwitchUsage = (nContextSwitchPut - S.nContextSwitchLastPut);
  1341. }
  1342. else
  1343. {
  1344. S.nContextSwitchUsage = MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - S.nContextSwitchLastPut + nContextSwitchPut;
  1345. }
  1346. S.nContextSwitchLastPut = nContextSwitchPut;
  1347. MicroProfileFrameState* pFramePut = &S.Frames[S.nFramePut];
  1348. MicroProfileFrameState* pFrameCurrent = &S.Frames[S.nFrameCurrent];
  1349. MicroProfileFrameState* pFrameNext = &S.Frames[nFrameNext];
  1350. pFramePut->nFrameStartCpu = MP_TICK();
  1351. pFramePut->nFrameStartGpu = (uint32_t)MicroProfileGpuInsertTimeStamp();
  1352. if(pFrameNext->nFrameStartGpu != -1)
  1353. pFrameNext->nFrameStartGpu = MicroProfileGpuGetTimeStamp((uint32_t)pFrameNext->nFrameStartGpu);
  1354. if(pFrameCurrent->nFrameStartGpu == -1)
  1355. pFrameCurrent->nFrameStartGpu = pFrameNext->nFrameStartGpu + 1;
  1356. uint64_t nFrameStartCpu = pFrameCurrent->nFrameStartCpu;
  1357. uint64_t nFrameEndCpu = pFrameNext->nFrameStartCpu;
  1358. {
  1359. uint64_t nTick = nFrameEndCpu - nFrameStartCpu;
  1360. S.nFlipTicks = nTick;
  1361. S.nFlipAggregate += nTick;
  1362. S.nFlipMax = MicroProfileMax(S.nFlipMax, nTick);
  1363. }
  1364. uint8_t* pTimerToGroup = &S.TimerToGroup[0];
  1365. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1366. {
  1367. MicroProfileThreadLog* pLog = S.Pool[i];
  1368. if(!pLog)
  1369. {
  1370. pFramePut->nLogStart[i] = 0;
  1371. }
  1372. else
  1373. {
  1374. uint32_t nPut = pLog->nPut.load(std::memory_order_acquire);
  1375. pFramePut->nLogStart[i] = nPut;
  1376. MP_ASSERT(nPut< MICROPROFILE_BUFFER_SIZE);
  1377. //need to keep last frame around to close timers. timers more than 1 frame old is ditched.
  1378. pLog->nGet.store(nPut, std::memory_order_relaxed);
  1379. }
  1380. }
  1381. if(S.nRunning)
  1382. {
  1383. uint64_t* pFrameGroup = &S.FrameGroup[0];
  1384. {
  1385. MICROPROFILE_SCOPE(g_MicroProfileClear);
  1386. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1387. {
  1388. S.Frame[i].nTicks = 0;
  1389. S.Frame[i].nCount = 0;
  1390. S.FrameExclusive[i] = 0;
  1391. }
  1392. for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  1393. {
  1394. pFrameGroup[i] = 0;
  1395. }
  1396. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1397. {
  1398. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1399. {
  1400. auto& Meta = S.MetaCounters[j];
  1401. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1402. {
  1403. Meta.nCounters[i] = 0;
  1404. }
  1405. }
  1406. }
  1407. }
  1408. {
  1409. MICROPROFILE_SCOPE(g_MicroProfileThreadLoop);
  1410. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1411. {
  1412. MicroProfileThreadLog* pLog = S.Pool[i];
  1413. if(!pLog)
  1414. continue;
  1415. uint8_t* pGroupStackPos = &pLog->nGroupStackPos[0];
  1416. int64_t nGroupTicks[MICROPROFILE_MAX_GROUPS] = {0};
  1417. uint32_t nPut = pFrameNext->nLogStart[i];
  1418. uint32_t nGet = pFrameCurrent->nLogStart[i];
  1419. uint32_t nRange[2][2] = { {0, 0}, {0, 0}, };
  1420. MicroProfileGetRange(nPut, nGet, nRange);
  1421. //fetch gpu results.
  1422. if(pLog->nGpu)
  1423. {
  1424. for(uint32_t j = 0; j < 2; ++j)
  1425. {
  1426. uint32_t nStart = nRange[j][0];
  1427. uint32_t nEnd = nRange[j][1];
  1428. for(uint32_t k = nStart; k < nEnd; ++k)
  1429. {
  1430. MicroProfileLogEntry L = pLog->Log[k];
  1431. if(MicroProfileLogType(L) < MP_LOG_META)
  1432. {
  1433. pLog->Log[k] = MicroProfileLogSetTick(L, MicroProfileGpuGetTimeStamp((uint32_t)MicroProfileLogGetTick(L)));
  1434. }
  1435. }
  1436. }
  1437. }
  1438. uint32_t* pStack = &pLog->nStack[0];
  1439. int64_t* pChildTickStack = &pLog->nChildTickStack[0];
  1440. uint32_t nStackPos = pLog->nStackPos;
  1441. for(uint32_t j = 0; j < 2; ++j)
  1442. {
  1443. uint32_t nStart = nRange[j][0];
  1444. uint32_t nEnd = nRange[j][1];
  1445. for(uint32_t k = nStart; k < nEnd; ++k)
  1446. {
  1447. MicroProfileLogEntry LE = pLog->Log[k];
  1448. int nType = MicroProfileLogType(LE);
  1449. if(MP_LOG_ENTER == nType)
  1450. {
  1451. int nTimer = MicroProfileLogTimerIndex(LE);
  1452. uint8_t nGroup = pTimerToGroup[nTimer];
  1453. MP_ASSERT(nStackPos < MICROPROFILE_STACK_MAX);
  1454. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1455. pGroupStackPos[nGroup]++;
  1456. pStack[nStackPos++] = k;
  1457. pChildTickStack[nStackPos] = 0;
  1458. }
  1459. else if(MP_LOG_META == nType)
  1460. {
  1461. if(nStackPos)
  1462. {
  1463. int64_t nMetaIndex = MicroProfileLogTimerIndex(LE);
  1464. int64_t nMetaCount = MicroProfileLogGetTick(LE);
  1465. MP_ASSERT(nMetaIndex < MICROPROFILE_META_MAX);
  1466. int64_t nCounter = MicroProfileLogTimerIndex(pLog->Log[pStack[nStackPos-1]]);
  1467. S.MetaCounters[nMetaIndex].nCounters[nCounter] += nMetaCount;
  1468. }
  1469. }
  1470. else if(MP_LOG_LEAVE == nType)
  1471. {
  1472. int nTimer = MicroProfileLogTimerIndex(LE);
  1473. uint8_t nGroup = pTimerToGroup[nTimer];
  1474. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1475. if(nStackPos)
  1476. {
  1477. int64_t nTickStart = pLog->Log[pStack[nStackPos-1]];
  1478. int64_t nTicks = MicroProfileLogTickDifference(nTickStart, LE);
  1479. int64_t nChildTicks = pChildTickStack[nStackPos];
  1480. nStackPos--;
  1481. pChildTickStack[nStackPos] += nTicks;
  1482. uint32_t nTimerIndex = MicroProfileLogTimerIndex(LE);
  1483. S.Frame[nTimerIndex].nTicks += nTicks;
  1484. S.FrameExclusive[nTimerIndex] += (nTicks-nChildTicks);
  1485. S.Frame[nTimerIndex].nCount += 1;
  1486. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1487. uint8_t nGroupStackPos = pGroupStackPos[nGroup];
  1488. if(nGroupStackPos)
  1489. {
  1490. nGroupStackPos--;
  1491. if(0 == nGroupStackPos)
  1492. {
  1493. nGroupTicks[nGroup] += nTicks;
  1494. }
  1495. pGroupStackPos[nGroup] = nGroupStackPos;
  1496. }
  1497. }
  1498. }
  1499. }
  1500. }
  1501. for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  1502. {
  1503. pLog->nGroupTicks[i] += nGroupTicks[i];
  1504. pFrameGroup[i] += nGroupTicks[i];
  1505. }
  1506. pLog->nStackPos = nStackPos;
  1507. }
  1508. }
  1509. {
  1510. MICROPROFILE_SCOPE(g_MicroProfileAccumulate);
  1511. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1512. {
  1513. S.AccumTimers[i].nTicks += S.Frame[i].nTicks;
  1514. S.AccumTimers[i].nCount += S.Frame[i].nCount;
  1515. S.AccumMaxTimers[i] = MicroProfileMax(S.AccumMaxTimers[i], S.Frame[i].nTicks);
  1516. S.AccumTimersExclusive[i] += S.FrameExclusive[i];
  1517. S.AccumMaxTimersExclusive[i] = MicroProfileMax(S.AccumMaxTimersExclusive[i], S.FrameExclusive[i]);
  1518. }
  1519. for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  1520. {
  1521. S.AccumGroup[i] += pFrameGroup[i];
  1522. S.AccumGroupMax[i] = MicroProfileMax(S.AccumGroupMax[i], pFrameGroup[i]);
  1523. }
  1524. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1525. {
  1526. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1527. {
  1528. auto& Meta = S.MetaCounters[j];
  1529. uint64_t nSum = 0;;
  1530. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1531. {
  1532. uint64_t nCounter = Meta.nCounters[i];
  1533. Meta.nAccumMax[i] = MicroProfileMax(Meta.nAccumMax[i], nCounter);
  1534. Meta.nAccum[i] += nCounter;
  1535. nSum += nCounter;
  1536. }
  1537. Meta.nSumAccum += nSum;
  1538. Meta.nSumAccumMax = MicroProfileMax(Meta.nSumAccumMax, nSum);
  1539. }
  1540. }
  1541. }
  1542. for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i)
  1543. {
  1544. if(S.Graph[i].nToken != MICROPROFILE_INVALID_TOKEN)
  1545. {
  1546. MicroProfileToken nToken = S.Graph[i].nToken;
  1547. S.Graph[i].nHistory[S.nGraphPut] = S.Frame[MicroProfileGetTimerIndex(nToken)].nTicks;
  1548. }
  1549. }
  1550. S.nGraphPut = (S.nGraphPut+1) % MICROPROFILE_GRAPH_HISTORY;
  1551. }
  1552. if(S.nRunning && S.nAggregateFlip <= ++S.nAggregateFlipCount)
  1553. {
  1554. nAggregateFlip = 1;
  1555. if(S.nAggregateFlip) // if 0 accumulate indefinitely
  1556. {
  1557. nAggregateClear = 1;
  1558. }
  1559. }
  1560. }
  1561. if(nAggregateFlip)
  1562. {
  1563. memcpy(&S.Aggregate[0], &S.AccumTimers[0], sizeof(S.Aggregate[0]) * S.nTotalTimers);
  1564. memcpy(&S.AggregateMax[0], &S.AccumMaxTimers[0], sizeof(S.AggregateMax[0]) * S.nTotalTimers);
  1565. memcpy(&S.AggregateExclusive[0], &S.AccumTimersExclusive[0], sizeof(S.AggregateExclusive[0]) * S.nTotalTimers);
  1566. memcpy(&S.AggregateMaxExclusive[0], &S.AccumMaxTimersExclusive[0], sizeof(S.AggregateMaxExclusive[0]) * S.nTotalTimers);
  1567. memcpy(&S.AggregateGroup[0], &S.AccumGroup[0], sizeof(S.AggregateGroup));
  1568. memcpy(&S.AggregateGroupMax[0], &S.AccumGroupMax[0], sizeof(S.AggregateGroup));
  1569. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1570. {
  1571. MicroProfileThreadLog* pLog = S.Pool[i];
  1572. if(!pLog)
  1573. continue;
  1574. memcpy(&pLog->nAggregateGroupTicks[0], &pLog->nGroupTicks[0], sizeof(pLog->nAggregateGroupTicks));
  1575. if(nAggregateClear)
  1576. {
  1577. memset(&pLog->nGroupTicks[0], 0, sizeof(pLog->nGroupTicks));
  1578. }
  1579. }
  1580. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1581. {
  1582. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1583. {
  1584. auto& Meta = S.MetaCounters[j];
  1585. memcpy(&Meta.nAggregateMax[0], &Meta.nAccumMax[0], sizeof(Meta.nAggregateMax[0]) * S.nTotalTimers);
  1586. memcpy(&Meta.nAggregate[0], &Meta.nAccum[0], sizeof(Meta.nAggregate[0]) * S.nTotalTimers);
  1587. Meta.nSumAggregate = Meta.nSumAccum;
  1588. Meta.nSumAggregateMax = Meta.nSumAccumMax;
  1589. if(nAggregateClear)
  1590. {
  1591. memset(&Meta.nAccumMax[0], 0, sizeof(Meta.nAccumMax[0]) * S.nTotalTimers);
  1592. memset(&Meta.nAccum[0], 0, sizeof(Meta.nAccum[0]) * S.nTotalTimers);
  1593. Meta.nSumAccum = 0;
  1594. Meta.nSumAccumMax = 0;
  1595. }
  1596. }
  1597. }
  1598. S.nAggregateFrames = S.nAggregateFlipCount;
  1599. S.nFlipAggregateDisplay = S.nFlipAggregate;
  1600. S.nFlipMaxDisplay = S.nFlipMax;
  1601. if(nAggregateClear)
  1602. {
  1603. memset(&S.AccumTimers[0], 0, sizeof(S.Aggregate[0]) * S.nTotalTimers);
  1604. memset(&S.AccumMaxTimers[0], 0, sizeof(S.AccumMaxTimers[0]) * S.nTotalTimers);
  1605. memset(&S.AccumTimersExclusive[0], 0, sizeof(S.AggregateExclusive[0]) * S.nTotalTimers);
  1606. memset(&S.AccumMaxTimersExclusive[0], 0, sizeof(S.AccumMaxTimersExclusive[0]) * S.nTotalTimers);
  1607. memset(&S.AccumGroup[0], 0, sizeof(S.AggregateGroup));
  1608. memset(&S.AccumGroupMax[0], 0, sizeof(S.AggregateGroup));
  1609. S.nAggregateFlipCount = 0;
  1610. S.nFlipAggregate = 0;
  1611. S.nFlipMax = 0;
  1612. S.nAggregateFlipTick = MP_TICK();
  1613. }
  1614. }
  1615. S.nAggregateClear = 0;
  1616. uint64_t nNewActiveGroup = 0;
  1617. if(S.nForceEnable || (S.nDisplay && S.nRunning))
  1618. nNewActiveGroup = S.nAllGroupsWanted ? S.nGroupMask : S.nActiveGroupWanted;
  1619. nNewActiveGroup |= S.nForceGroup;
  1620. nNewActiveGroup |= S.nForceGroupUI;
  1621. if(S.nActiveGroup != nNewActiveGroup)
  1622. S.nActiveGroup = nNewActiveGroup;
  1623. uint32_t nNewActiveBars = 0;
  1624. if(S.nDisplay && S.nRunning)
  1625. nNewActiveBars = S.nBars;
  1626. if(S.nForceMetaCounters)
  1627. {
  1628. for(int i = 0; i < MICROPROFILE_META_MAX; ++i)
  1629. {
  1630. if(S.MetaCounters[i].pName)
  1631. {
  1632. nNewActiveBars |= (MP_DRAW_META_FIRST<<i);
  1633. }
  1634. }
  1635. }
  1636. if(nNewActiveBars != S.nActiveBars)
  1637. S.nActiveBars = nNewActiveBars;
  1638. }
  1639. void MicroProfileSetForceEnable(bool bEnable)
  1640. {
  1641. S.nForceEnable = bEnable ? 1 : 0;
  1642. }
  1643. bool MicroProfileGetForceEnable()
  1644. {
  1645. return S.nForceEnable != 0;
  1646. }
  1647. void MicroProfileSetEnableAllGroups(bool bEnableAllGroups)
  1648. {
  1649. S.nAllGroupsWanted = bEnableAllGroups ? 1 : 0;
  1650. }
  1651. inline void MicroProfileEnableCategory(const char* pCategory, bool bEnabled)
  1652. {
  1653. int nCategoryIndex = -1;
  1654. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1655. {
  1656. if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName))
  1657. {
  1658. nCategoryIndex = (int)i;
  1659. break;
  1660. }
  1661. }
  1662. if(nCategoryIndex >= 0)
  1663. {
  1664. if(bEnabled)
  1665. {
  1666. S.nActiveGroupWanted |= S.CategoryInfo[nCategoryIndex].nGroupMask;
  1667. }
  1668. else
  1669. {
  1670. S.nActiveGroupWanted &= ~S.CategoryInfo[nCategoryIndex].nGroupMask;
  1671. }
  1672. }
  1673. }
  1674. void MicroProfileEnableCategory(const char* pCategory)
  1675. {
  1676. MicroProfileEnableCategory(pCategory, true);
  1677. }
  1678. void MicroProfileDisableCategory(const char* pCategory)
  1679. {
  1680. MicroProfileEnableCategory(pCategory, false);
  1681. }
  1682. bool MicroProfileGetEnableAllGroups()
  1683. {
  1684. return 0 != S.nAllGroupsWanted;
  1685. }
  1686. void MicroProfileSetForceMetaCounters(bool bForce)
  1687. {
  1688. S.nForceMetaCounters = bForce ? 1 : 0;
  1689. }
  1690. bool MicroProfileGetForceMetaCounters()
  1691. {
  1692. return 0 != S.nForceMetaCounters;
  1693. }
  1694. void MicroProfileEnableMetaCounter(const char* pMeta)
  1695. {
  1696. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1697. {
  1698. if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta))
  1699. {
  1700. S.nBars |= (MP_DRAW_META_FIRST<<i);
  1701. return;
  1702. }
  1703. }
  1704. }
  1705. void MicroProfileDisableMetaCounter(const char* pMeta)
  1706. {
  1707. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1708. {
  1709. if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta))
  1710. {
  1711. S.nBars &= ~(MP_DRAW_META_FIRST<<i);
  1712. return;
  1713. }
  1714. }
  1715. }
  1716. void MicroProfileSetAggregateFrames(int nFrames)
  1717. {
  1718. S.nAggregateFlip = (uint32_t)nFrames;
  1719. if(0 == nFrames)
  1720. {
  1721. S.nAggregateClear = 1;
  1722. }
  1723. }
  1724. int MicroProfileGetAggregateFrames()
  1725. {
  1726. return S.nAggregateFlip;
  1727. }
  1728. int MicroProfileGetCurrentAggregateFrames()
  1729. {
  1730. return int(S.nAggregateFlip ? S.nAggregateFlip : S.nAggregateFlipCount);
  1731. }
  1732. void MicroProfileForceEnableGroup(const char* pGroup, MicroProfileTokenType Type)
  1733. {
  1734. MicroProfileInit();
  1735. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1736. uint16_t nGroup = MicroProfileGetGroup(pGroup, Type);
  1737. S.nForceGroup |= (1ll << nGroup);
  1738. }
  1739. void MicroProfileForceDisableGroup(const char* pGroup, MicroProfileTokenType Type)
  1740. {
  1741. MicroProfileInit();
  1742. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1743. uint16_t nGroup = MicroProfileGetGroup(pGroup, Type);
  1744. S.nForceGroup &= ~(1ll << nGroup);
  1745. }
  1746. inline void MicroProfileCalcAllTimers(float* pTimers, float* pAverage, float* pMax, float* pCallAverage, float* pExclusive, float* pAverageExclusive, float* pMaxExclusive, float* pTotal, uint32_t nSize)
  1747. {
  1748. for(uint32_t i = 0; i < S.nTotalTimers && i < nSize; ++i)
  1749. {
  1750. const uint32_t nGroupId = S.TimerInfo[i].nGroupIndex;
  1751. const float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupId].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu());
  1752. uint32_t nTimer = i;
  1753. uint32_t nIdx = i * 2;
  1754. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  1755. uint32_t nAggregateCount = S.Aggregate[nTimer].nCount ? S.Aggregate[nTimer].nCount : 1;
  1756. float fToPrc = S.fRcpReferenceTime;
  1757. float fMs = fToMs * (S.Frame[nTimer].nTicks);
  1758. float fPrc = MicroProfileMin(fMs * fToPrc, 1.f);
  1759. float fAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateFrames);
  1760. float fAveragePrc = MicroProfileMin(fAverageMs * fToPrc, 1.f);
  1761. float fMaxMs = fToMs * (S.AggregateMax[nTimer]);
  1762. float fMaxPrc = MicroProfileMin(fMaxMs * fToPrc, 1.f);
  1763. float fCallAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateCount);
  1764. float fCallAveragePrc = MicroProfileMin(fCallAverageMs * fToPrc, 1.f);
  1765. float fMsExclusive = fToMs * (S.FrameExclusive[nTimer]);
  1766. float fPrcExclusive = MicroProfileMin(fMsExclusive * fToPrc, 1.f);
  1767. float fAverageMsExclusive = fToMs * (S.AggregateExclusive[nTimer] / nAggregateFrames);
  1768. float fAveragePrcExclusive = MicroProfileMin(fAverageMsExclusive * fToPrc, 1.f);
  1769. float fMaxMsExclusive = fToMs * (S.AggregateMaxExclusive[nTimer]);
  1770. float fMaxPrcExclusive = MicroProfileMin(fMaxMsExclusive * fToPrc, 1.f);
  1771. float fTotalMs = fToMs * S.Aggregate[nTimer].nTicks;
  1772. pTimers[nIdx] = fMs;
  1773. pTimers[nIdx+1] = fPrc;
  1774. pAverage[nIdx] = fAverageMs;
  1775. pAverage[nIdx+1] = fAveragePrc;
  1776. pMax[nIdx] = fMaxMs;
  1777. pMax[nIdx+1] = fMaxPrc;
  1778. pCallAverage[nIdx] = fCallAverageMs;
  1779. pCallAverage[nIdx+1] = fCallAveragePrc;
  1780. pExclusive[nIdx] = fMsExclusive;
  1781. pExclusive[nIdx+1] = fPrcExclusive;
  1782. pAverageExclusive[nIdx] = fAverageMsExclusive;
  1783. pAverageExclusive[nIdx+1] = fAveragePrcExclusive;
  1784. pMaxExclusive[nIdx] = fMaxMsExclusive;
  1785. pMaxExclusive[nIdx+1] = fMaxPrcExclusive;
  1786. pTotal[nIdx] = fTotalMs;
  1787. pTotal[nIdx+1] = 0.f;
  1788. }
  1789. }
  1790. void MicroProfileTogglePause()
  1791. {
  1792. S.nToggleRunning = 1;
  1793. }
  1794. float MicroProfileGetTime(const char* pGroup, const char* pName)
  1795. {
  1796. MicroProfileToken nToken = MicroProfileFindToken(pGroup, pName);
  1797. if(nToken == MICROPROFILE_INVALID_TOKEN)
  1798. {
  1799. return 0.f;
  1800. }
  1801. uint32_t nTimerIndex = MicroProfileGetTimerIndex(nToken);
  1802. uint32_t nGroupIndex = MicroProfileGetGroupIndex(nToken);
  1803. float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupIndex].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu());
  1804. return S.Frame[nTimerIndex].nTicks * fToMs;
  1805. }
  1806. void MicroProfileContextSwitchSearch(uint32_t* pContextSwitchStart, uint32_t* pContextSwitchEnd, uint64_t nBaseTicksCpu, uint64_t nBaseTicksEndCpu)
  1807. {
  1808. MICROPROFILE_SCOPE(g_MicroProfileContextSwitchSearch);
  1809. uint32_t nContextSwitchPut = S.nContextSwitchPut;
  1810. uint64_t nContextSwitchStart, nContextSwitchEnd;
  1811. nContextSwitchStart = nContextSwitchEnd = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - 1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1812. int64_t nSearchEnd = nBaseTicksEndCpu + MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu());
  1813. int64_t nSearchBegin = nBaseTicksCpu - MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu());
  1814. for(uint32_t i = 0; i < MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; ++i)
  1815. {
  1816. uint32_t nIndex = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - (i+1)) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1817. MicroProfileContextSwitch& CS = S.ContextSwitch[nIndex];
  1818. if(CS.nTicks > nSearchEnd)
  1819. {
  1820. nContextSwitchEnd = nIndex;
  1821. }
  1822. if(CS.nTicks > nSearchBegin)
  1823. {
  1824. nContextSwitchStart = nIndex;
  1825. }
  1826. }
  1827. *pContextSwitchStart = nContextSwitchStart;
  1828. *pContextSwitchEnd = nContextSwitchEnd;
  1829. }
  1830. #if MICROPROFILE_WEBSERVER
  1831. #define MICROPROFILE_EMBED_HTML
  1832. extern const char* g_MicroProfileHtml_begin[];
  1833. extern size_t g_MicroProfileHtml_begin_sizes[];
  1834. extern size_t g_MicroProfileHtml_begin_count;
  1835. extern const char* g_MicroProfileHtml_end[];
  1836. extern size_t g_MicroProfileHtml_end_sizes[];
  1837. extern size_t g_MicroProfileHtml_end_count;
  1838. typedef void MicroProfileWriteCallback(void* Handle, size_t size, const char* pData);
  1839. uint32_t MicroProfileWebServerPort()
  1840. {
  1841. return S.nWebServerPort;
  1842. }
  1843. void MicroProfileDumpFile(const char* pHtml, const char* pCsv)
  1844. {
  1845. S.nDumpFileNextFrame = 0;
  1846. if(pHtml)
  1847. {
  1848. uint32_t nLen = strlen(pHtml);
  1849. if(nLen > sizeof(S.HtmlDumpPath)-1)
  1850. {
  1851. return;
  1852. }
  1853. memcpy(S.HtmlDumpPath, pHtml, nLen+1);
  1854. S.nDumpFileNextFrame |= 1;
  1855. }
  1856. if(pCsv)
  1857. {
  1858. uint32_t nLen = strlen(pCsv);
  1859. if(nLen > sizeof(S.CsvDumpPath)-1)
  1860. {
  1861. return;
  1862. }
  1863. memcpy(S.CsvDumpPath, pCsv, nLen+1);
  1864. S.nDumpFileNextFrame |= 2;
  1865. }
  1866. }
  1867. void MicroProfilePrintf(MicroProfileWriteCallback CB, void* Handle, const char* pFmt, ...)
  1868. {
  1869. char buffer[32*1024];
  1870. va_list args;
  1871. va_start (args, pFmt);
  1872. #ifdef _WIN32
  1873. size_t size = vsprintf_s(buffer, pFmt, args);
  1874. #else
  1875. size_t size = vsnprintf(buffer, sizeof(buffer)-1, pFmt, args);
  1876. #endif
  1877. CB(Handle, size, &buffer[0]);
  1878. va_end (args);
  1879. }
  1880. #define printf(...) MicroProfilePrintf(CB, Handle, __VA_ARGS__)
  1881. void MicroProfileDumpCsv(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames)
  1882. {
  1883. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  1884. float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  1885. float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu());
  1886. printf("frames,%d\n", nAggregateFrames);
  1887. printf("group,name,average,max,callaverage\n");
  1888. uint32_t nNumTimers = S.nTotalTimers;
  1889. uint32_t nBlockSize = 2 * nNumTimers;
  1890. float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float));
  1891. float* pAverage = pTimers + nBlockSize;
  1892. float* pMax = pTimers + 2 * nBlockSize;
  1893. float* pCallAverage = pTimers + 3 * nBlockSize;
  1894. float* pTimersExclusive = pTimers + 4 * nBlockSize;
  1895. float* pAverageExclusive = pTimers + 5 * nBlockSize;
  1896. float* pMaxExclusive = pTimers + 6 * nBlockSize;
  1897. float* pTotal = pTimers + 7 * nBlockSize;
  1898. MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers);
  1899. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1900. {
  1901. uint32_t nIdx = i * 2;
  1902. printf("\"%s\",\"%s\",%f,%f,%f\n", S.TimerInfo[i].pName, S.GroupInfo[S.TimerInfo[i].nGroupIndex].pName, pAverage[nIdx], pMax[nIdx], pCallAverage[nIdx]);
  1903. }
  1904. printf("\n\n");
  1905. printf("group,average,max,total\n");
  1906. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1907. {
  1908. const char* pGroupName = S.GroupInfo[j].pName;
  1909. float fToMs = S.GroupInfo[j].Type == MicroProfileTokenTypeGpu ? fToMsGPU : fToMsCPU;
  1910. if(pGroupName[0] != '\0')
  1911. {
  1912. printf("\"%s\",%.3f,%.3f,%.3f\n", pGroupName, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j]);
  1913. }
  1914. }
  1915. printf("\n\n");
  1916. printf("group,thread,average,total\n");
  1917. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1918. {
  1919. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  1920. {
  1921. if(S.Pool[i])
  1922. {
  1923. const char* pThreadName = &S.Pool[i]->ThreadName[0];
  1924. // MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i);
  1925. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  1926. {
  1927. uint64_t nTicks = S.Pool[i]->nAggregateGroupTicks[j];
  1928. float fTime = nTicks / nAggregateFrames * fToMs;
  1929. float fTimeTotal = nTicks * fToMs;
  1930. if(fTimeTotal > 0.01f)
  1931. {
  1932. const char* pGroupName = S.GroupInfo[j].pName;
  1933. printf("\"%s\",\"%s\",%.3f,%.3f\n", pGroupName, pThreadName, fTime, fTimeTotal);
  1934. }
  1935. }
  1936. }
  1937. }
  1938. }
  1939. printf("\n\n");
  1940. printf("frametimecpu\n");
  1941. const uint32_t nCount = MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3;
  1942. const uint32_t nStart = S.nFrameCurrent;
  1943. for(uint32_t i = nCount; i > 0; i--)
  1944. {
  1945. uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY;
  1946. uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1947. uint64_t nTicks = S.Frames[nFrameNext].nFrameStartCpu - S.Frames[nFrame].nFrameStartCpu;
  1948. printf("%f,", nTicks * fToMsCPU);
  1949. }
  1950. printf("\n");
  1951. printf("\n\n");
  1952. printf("frametimegpu\n");
  1953. for(uint32_t i = nCount; i > 0; i--)
  1954. {
  1955. uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY;
  1956. uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1957. uint64_t nTicks = S.Frames[nFrameNext].nFrameStartGpu - S.Frames[nFrame].nFrameStartGpu;
  1958. printf("%f,", nTicks * fToMsGPU);
  1959. }
  1960. printf("\n\n");
  1961. printf("Meta\n");//only single frame snapshot
  1962. printf("name,average,max,total\n");
  1963. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  1964. {
  1965. if(S.MetaCounters[j].pName)
  1966. {
  1967. printf("\"%s\",%f,%lld,%lld\n",S.MetaCounters[j].pName, S.MetaCounters[j].nSumAggregate / (float)nAggregateFrames, S.MetaCounters[j].nSumAggregateMax,S.MetaCounters[j].nSumAggregate);
  1968. }
  1969. }
  1970. }
  1971. #undef printf
  1972. void MicroProfileDumpHtml(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames, const char* pHost)
  1973. {
  1974. uint32_t nRunning = S.nRunning;
  1975. S.nRunning = 0;
  1976. //stall pushing of timers
  1977. uint64_t nActiveGroup = S.nActiveGroup;
  1978. S.nActiveGroup = 0;
  1979. S.nPauseTicks = MP_TICK();
  1980. for(size_t i = 0; i < g_MicroProfileHtml_begin_count; ++i)
  1981. {
  1982. CB(Handle, g_MicroProfileHtml_begin_sizes[i]-1, g_MicroProfileHtml_begin[i]);
  1983. }
  1984. //dump info
  1985. uint64_t nTicks = MP_TICK();
  1986. float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  1987. float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu());
  1988. float fAggregateMs = fToMsCPU * (nTicks - S.nAggregateFlipTick);
  1989. MicroProfilePrintf(CB, Handle, "var DumpHost = '%s';\n", pHost ? pHost : "");
  1990. time_t CaptureTime;
  1991. time(&CaptureTime);
  1992. MicroProfilePrintf(CB, Handle, "var DumpUtcCaptureTime = %ld;\n", CaptureTime);
  1993. MicroProfilePrintf(CB, Handle, "var AggregateInfo = {'Frames':%d, 'Time':%f};\n", S.nAggregateFrames, fAggregateMs);
  1994. //categories
  1995. MicroProfilePrintf(CB, Handle, "var CategoryInfo = Array(%d);\n",S.nCategoryCount);
  1996. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1997. {
  1998. MicroProfilePrintf(CB, Handle, "CategoryInfo[%d] = \"%s\";\n", i, S.CategoryInfo[i].pName);
  1999. }
  2000. //groups
  2001. MicroProfilePrintf(CB, Handle, "var GroupInfo = Array(%d);\n\n",S.nGroupCount);
  2002. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  2003. float fRcpAggregateFrames = 1.f / nAggregateFrames;
  2004. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2005. {
  2006. MP_ASSERT(i == S.GroupInfo[i].nGroupIndex);
  2007. float fToMs = S.GroupInfo[i].Type == MicroProfileTokenTypeCpu ? fToMsCPU : fToMsGPU;
  2008. MicroProfilePrintf(CB, Handle, "GroupInfo[%d] = MakeGroup(%d, \"%s\", %d, %d, %d, %f, %f, %f, '#%02x%02x%02x');\n",
  2009. S.GroupInfo[i].nGroupIndex,
  2010. S.GroupInfo[i].nGroupIndex,
  2011. S.GroupInfo[i].pName,
  2012. S.GroupInfo[i].nCategory,
  2013. S.GroupInfo[i].nNumTimers,
  2014. S.GroupInfo[i].Type == MicroProfileTokenTypeGpu?1:0,
  2015. fToMs * S.AggregateGroup[i],
  2016. fToMs * S.AggregateGroup[i] / nAggregateFrames,
  2017. fToMs * S.AggregateGroupMax[i],
  2018. MICROPROFILE_UNPACK_RED(S.GroupInfo[i].nColor) & 0xff,
  2019. MICROPROFILE_UNPACK_GREEN(S.GroupInfo[i].nColor) & 0xff,
  2020. MICROPROFILE_UNPACK_BLUE(S.GroupInfo[i].nColor) & 0xff);
  2021. }
  2022. //timers
  2023. uint32_t nNumTimers = S.nTotalTimers;
  2024. uint32_t nBlockSize = 2 * nNumTimers;
  2025. float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float));
  2026. float* pAverage = pTimers + nBlockSize;
  2027. float* pMax = pTimers + 2 * nBlockSize;
  2028. float* pCallAverage = pTimers + 3 * nBlockSize;
  2029. float* pTimersExclusive = pTimers + 4 * nBlockSize;
  2030. float* pAverageExclusive = pTimers + 5 * nBlockSize;
  2031. float* pMaxExclusive = pTimers + 6 * nBlockSize;
  2032. float* pTotal = pTimers + 7 * nBlockSize;
  2033. MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers);
  2034. MicroProfilePrintf(CB, Handle, "\nvar TimerInfo = Array(%d);\n\n", S.nTotalTimers);
  2035. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2036. {
  2037. uint32_t nIdx = i * 2;
  2038. MP_ASSERT(i == S.TimerInfo[i].nTimerIndex);
  2039. MicroProfilePrintf(CB, Handle, "var Meta%d = [", i);
  2040. bool bOnce = true;
  2041. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2042. {
  2043. if(S.MetaCounters[j].pName)
  2044. {
  2045. uint32_t lala = S.MetaCounters[j].nCounters[i];
  2046. MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", lala);
  2047. bOnce = false;
  2048. }
  2049. }
  2050. MicroProfilePrintf(CB, Handle, "];\n");
  2051. MicroProfilePrintf(CB, Handle, "var MetaAvg%d = [", i);
  2052. bOnce = true;
  2053. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2054. {
  2055. if(S.MetaCounters[j].pName)
  2056. {
  2057. MicroProfilePrintf(CB, Handle, bOnce ? "%f" : ",%f", fRcpAggregateFrames * S.MetaCounters[j].nAggregate[i]);
  2058. bOnce = false;
  2059. }
  2060. }
  2061. MicroProfilePrintf(CB, Handle, "];\n");
  2062. MicroProfilePrintf(CB, Handle, "var MetaMax%d = [", i);
  2063. bOnce = true;
  2064. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2065. {
  2066. if(S.MetaCounters[j].pName)
  2067. {
  2068. MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", S.MetaCounters[j].nAggregateMax[i]);
  2069. bOnce = false;
  2070. }
  2071. }
  2072. MicroProfilePrintf(CB, Handle, "];\n");
  2073. uint32_t nColor = S.TimerInfo[i].nColor;
  2074. uint32_t nColorDark = (nColor >> 1) & ~0x80808080;
  2075. 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,
  2076. MICROPROFILE_UNPACK_RED(nColor) & 0xff,
  2077. MICROPROFILE_UNPACK_GREEN(nColor) & 0xff,
  2078. MICROPROFILE_UNPACK_BLUE(nColor) & 0xff,
  2079. MICROPROFILE_UNPACK_RED(nColorDark) & 0xff,
  2080. MICROPROFILE_UNPACK_GREEN(nColorDark) & 0xff,
  2081. MICROPROFILE_UNPACK_BLUE(nColorDark) & 0xff,
  2082. pAverage[nIdx],
  2083. pMax[nIdx],
  2084. pAverageExclusive[nIdx],
  2085. pMaxExclusive[nIdx],
  2086. pCallAverage[nIdx],
  2087. S.Aggregate[i].nCount,
  2088. pTotal[nIdx],
  2089. i,i,i);
  2090. }
  2091. MicroProfilePrintf(CB, Handle, "\nvar ThreadNames = [");
  2092. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2093. {
  2094. if(S.Pool[i])
  2095. {
  2096. MicroProfilePrintf(CB, Handle, "'%s',", S.Pool[i]->ThreadName);
  2097. }
  2098. else
  2099. {
  2100. MicroProfilePrintf(CB, Handle, "'Thread %d',", i);
  2101. }
  2102. }
  2103. MicroProfilePrintf(CB, Handle, "];\n\n");
  2104. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2105. {
  2106. if(S.Pool[i])
  2107. {
  2108. MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i);
  2109. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  2110. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  2111. {
  2112. MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j]/nAggregateFrames * fToMs);
  2113. }
  2114. MicroProfilePrintf(CB, Handle, "];\n");
  2115. }
  2116. }
  2117. MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeArray = [");
  2118. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2119. {
  2120. if(S.Pool[i])
  2121. {
  2122. MicroProfilePrintf(CB, Handle, "ThreadGroupTime%d,", i);
  2123. }
  2124. }
  2125. MicroProfilePrintf(CB, Handle, "];\n");
  2126. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2127. {
  2128. if(S.Pool[i])
  2129. {
  2130. MicroProfilePrintf(CB, Handle, "var ThreadGroupTimeTotal%d = [", i);
  2131. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  2132. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  2133. {
  2134. MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j] * fToMs);
  2135. }
  2136. MicroProfilePrintf(CB, Handle, "];\n");
  2137. }
  2138. }
  2139. MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeTotalArray = [");
  2140. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2141. {
  2142. if(S.Pool[i])
  2143. {
  2144. MicroProfilePrintf(CB, Handle, "ThreadGroupTimeTotal%d,", i);
  2145. }
  2146. }
  2147. MicroProfilePrintf(CB, Handle, "];");
  2148. MicroProfilePrintf(CB, Handle, "\nvar ThreadIds = [");
  2149. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2150. {
  2151. if(S.Pool[i])
  2152. {
  2153. ThreadIdType ThreadId = S.Pool[i]->nThreadId;
  2154. if(!ThreadId)
  2155. {
  2156. ThreadId = (ThreadIdType)-1;
  2157. }
  2158. MicroProfilePrintf(CB, Handle, "%d,", ThreadId);
  2159. }
  2160. else
  2161. {
  2162. MicroProfilePrintf(CB, Handle, "-1,", i);
  2163. }
  2164. }
  2165. MicroProfilePrintf(CB, Handle, "];\n\n");
  2166. MicroProfilePrintf(CB, Handle, "\nvar MetaNames = [");
  2167. for(int i = 0; i < MICROPROFILE_META_MAX; ++i)
  2168. {
  2169. if(S.MetaCounters[i].pName)
  2170. {
  2171. MicroProfilePrintf(CB, Handle, "'%s',", S.MetaCounters[i].pName);
  2172. }
  2173. }
  2174. MicroProfilePrintf(CB, Handle, "];\n\n");
  2175. uint32_t nNumFrames = (MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3); //leave a few to not overwrite
  2176. nNumFrames = MicroProfileMin(nNumFrames, (uint32_t)nMaxFrames);
  2177. uint32_t nFirstFrame = (S.nFrameCurrent + MICROPROFILE_MAX_FRAME_HISTORY - nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY;
  2178. uint32_t nLastFrame = (nFirstFrame + nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY;
  2179. MP_ASSERT(nLastFrame == (S.nFrameCurrent % MICROPROFILE_MAX_FRAME_HISTORY));
  2180. MP_ASSERT(nFirstFrame < MICROPROFILE_MAX_FRAME_HISTORY);
  2181. MP_ASSERT(nLastFrame < MICROPROFILE_MAX_FRAME_HISTORY);
  2182. const int64_t nTickStart = S.Frames[nFirstFrame].nFrameStartCpu;
  2183. const int64_t nTickEnd = S.Frames[nLastFrame].nFrameStartCpu;
  2184. int64_t nTickStartGpu = S.Frames[nFirstFrame].nFrameStartGpu;
  2185. int64_t nTickReferenceCpu, nTickReferenceGpu;
  2186. int64_t nTicksPerSecondCpu = MicroProfileTicksPerSecondCpu();
  2187. int64_t nTicksPerSecondGpu = MicroProfileTicksPerSecondGpu();
  2188. int nTickReference = 0;
  2189. if(MicroProfileGetGpuTickReference(&nTickReferenceCpu, &nTickReferenceGpu))
  2190. {
  2191. nTickStartGpu = (nTickStart - nTickReferenceCpu) * nTicksPerSecondGpu / nTicksPerSecondCpu + nTickReferenceGpu;
  2192. nTickReference = 1;
  2193. }
  2194. #if MICROPROFILE_DEBUG
  2195. printf("dumping %d frames\n", nNumFrames);
  2196. printf("dumping frame %d to %d\n", nFirstFrame, nLastFrame);
  2197. #endif
  2198. uint32_t* nTimerCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers);
  2199. memset(nTimerCounter, 0, sizeof(uint32_t) * S.nTotalTimers);
  2200. MicroProfilePrintf(CB, Handle, "var Frames = Array(%d);\n", nNumFrames);
  2201. for(uint32_t i = 0; i < nNumFrames; ++i)
  2202. {
  2203. uint32_t nFrameIndex = (nFirstFrame + i) % MICROPROFILE_MAX_FRAME_HISTORY;
  2204. uint32_t nFrameIndexNext = (nFrameIndex + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  2205. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2206. {
  2207. MicroProfileThreadLog* pLog = S.Pool[j];
  2208. int64_t nStartTickBase = pLog->nGpu ? nTickStartGpu : nTickStart;
  2209. uint32_t nLogStart = S.Frames[nFrameIndex].nLogStart[j];
  2210. uint32_t nLogEnd = S.Frames[nFrameIndexNext].nLogStart[j];
  2211. float fToMsCpu = MicroProfileTickToMsMultiplier(nTicksPerSecondCpu);
  2212. float fToMsBase = MicroProfileTickToMsMultiplier(pLog->nGpu ? nTicksPerSecondGpu : nTicksPerSecondCpu);
  2213. MicroProfilePrintf(CB, Handle, "var ts_%d_%d = [", i, j);
  2214. if(nLogStart != nLogEnd)
  2215. {
  2216. uint32_t k = nLogStart;
  2217. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2218. float fToMs = nLogType == MP_LOG_GPU_EXTRA ? fToMsCpu : fToMsBase;
  2219. int64_t nStartTick = nLogType == MP_LOG_GPU_EXTRA ? nTickStart : nStartTickBase;
  2220. float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs;
  2221. MicroProfilePrintf(CB, Handle, "%f", fTime);
  2222. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2223. {
  2224. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2225. float fToMs = nLogType == MP_LOG_GPU_EXTRA ? fToMsCpu : fToMsBase;
  2226. nStartTick = nLogType == MP_LOG_GPU_EXTRA ? nTickStart : nStartTickBase;
  2227. float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs;
  2228. MicroProfilePrintf(CB, Handle, ",%f", fTime);
  2229. }
  2230. }
  2231. MicroProfilePrintf(CB, Handle, "];\n");
  2232. MicroProfilePrintf(CB, Handle, "var tt_%d_%d = [", i, j);
  2233. if(nLogStart != nLogEnd)
  2234. {
  2235. uint32_t k = nLogStart;
  2236. MicroProfilePrintf(CB, Handle, "%d", MicroProfileLogType(pLog->Log[k]));
  2237. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2238. {
  2239. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2240. if(nLogType == MP_LOG_META)
  2241. {
  2242. //for meta, store the count + 3, which is the tick part
  2243. nLogType = 3 + MicroProfileLogGetTick(pLog->Log[k]);
  2244. }
  2245. MicroProfilePrintf(CB, Handle, ",%d", nLogType);
  2246. }
  2247. }
  2248. MicroProfilePrintf(CB, Handle, "];\n");
  2249. MicroProfilePrintf(CB, Handle, "var ti_%d_%d = [", i, j);
  2250. if(nLogStart != nLogEnd)
  2251. {
  2252. uint32_t k = nLogStart;
  2253. MicroProfilePrintf(CB, Handle, "%d", (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]));
  2254. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2255. {
  2256. uint32_t nTimerIndex = (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]);
  2257. MicroProfilePrintf(CB, Handle, ",%d", nTimerIndex);
  2258. nTimerCounter[nTimerIndex]++;
  2259. }
  2260. }
  2261. MicroProfilePrintf(CB, Handle, "];\n");
  2262. }
  2263. MicroProfilePrintf(CB, Handle, "var ts%d = [", i);
  2264. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2265. {
  2266. MicroProfilePrintf(CB, Handle, "ts_%d_%d,", i, j);
  2267. }
  2268. MicroProfilePrintf(CB, Handle, "];\n");
  2269. MicroProfilePrintf(CB, Handle, "var tt%d = [", i);
  2270. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2271. {
  2272. MicroProfilePrintf(CB, Handle, "tt_%d_%d,", i, j);
  2273. }
  2274. MicroProfilePrintf(CB, Handle, "];\n");
  2275. MicroProfilePrintf(CB, Handle, "var ti%d = [", i);
  2276. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2277. {
  2278. MicroProfilePrintf(CB, Handle, "ti_%d_%d,", i, j);
  2279. }
  2280. MicroProfilePrintf(CB, Handle, "];\n");
  2281. int64_t nFrameStart = S.Frames[nFrameIndex].nFrameStartCpu;
  2282. int64_t nFrameEnd = S.Frames[nFrameIndexNext].nFrameStartCpu;
  2283. float fToMs = MicroProfileTickToMsMultiplier(nTicksPerSecondCpu);
  2284. float fFrameMs = MicroProfileLogTickDifference(nTickStart, nFrameStart) * fToMs;
  2285. float fFrameEndMs = MicroProfileLogTickDifference(nTickStart, nFrameEnd) * fToMs;
  2286. float fFrameGpuMs = 0;
  2287. float fFrameGpuEndMs = 0;
  2288. if(nTickReference)
  2289. {
  2290. fFrameGpuMs = MicroProfileLogTickDifference(nTickStartGpu, S.Frames[nFrameIndex].nFrameStartGpu) * fToMsGPU;
  2291. fFrameGpuEndMs = MicroProfileLogTickDifference(nTickStartGpu, S.Frames[nFrameIndexNext].nFrameStartGpu) * fToMsGPU;
  2292. }
  2293. 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);
  2294. }
  2295. uint32_t nContextSwitchStart = 0;
  2296. uint32_t nContextSwitchEnd = 0;
  2297. MicroProfileContextSwitchSearch(&nContextSwitchStart, &nContextSwitchEnd, nTickStart, nTickEnd);
  2298. uint32_t nWrittenBefore = S.nWebServerDataSent;
  2299. MicroProfilePrintf(CB, Handle, "var CSwitchThreadInOutCpu = [");
  2300. for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE)
  2301. {
  2302. MicroProfileContextSwitch CS = S.ContextSwitch[j];
  2303. int nCpu = CS.nCpu;
  2304. MicroProfilePrintf(CB, Handle, "%d,%d,%d,", CS.nThreadIn, CS.nThreadOut, nCpu);
  2305. }
  2306. MicroProfilePrintf(CB, Handle, "];\n");
  2307. MicroProfilePrintf(CB, Handle, "var CSwitchTime = [");
  2308. float fToMsCpu = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  2309. for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE)
  2310. {
  2311. MicroProfileContextSwitch CS = S.ContextSwitch[j];
  2312. float fTime = MicroProfileLogTickDifference(nTickStart, CS.nTicks) * fToMsCpu;
  2313. MicroProfilePrintf(CB, Handle, "%f,", fTime);
  2314. }
  2315. MicroProfilePrintf(CB, Handle, "];\n");
  2316. uint32_t nWrittenAfter = S.nWebServerDataSent;
  2317. MicroProfilePrintf(CB, Handle, "//CSwitch Size %d\n", nWrittenAfter - nWrittenBefore);
  2318. for(size_t i = 0; i < g_MicroProfileHtml_end_count; ++i)
  2319. {
  2320. CB(Handle, g_MicroProfileHtml_end_sizes[i]-1, g_MicroProfileHtml_end[i]);
  2321. }
  2322. uint32_t* nGroupCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount);
  2323. memset(nGroupCounter, 0, sizeof(uint32_t) * S.nGroupCount);
  2324. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2325. {
  2326. uint32_t nGroupIndex = S.TimerInfo[i].nGroupIndex;
  2327. nGroupCounter[nGroupIndex] += nTimerCounter[i];
  2328. }
  2329. uint32_t* nGroupCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount);
  2330. uint32_t* nTimerCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers);
  2331. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2332. {
  2333. nGroupCounterSort[i] = i;
  2334. }
  2335. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2336. {
  2337. nTimerCounterSort[i] = i;
  2338. }
  2339. std::sort(nGroupCounterSort, nGroupCounterSort + S.nGroupCount,
  2340. [nGroupCounter](const uint32_t l, const uint32_t r)
  2341. {
  2342. return nGroupCounter[l] > nGroupCounter[r];
  2343. }
  2344. );
  2345. std::sort(nTimerCounterSort, nTimerCounterSort + S.nTotalTimers,
  2346. [nTimerCounter](const uint32_t l, const uint32_t r)
  2347. {
  2348. return nTimerCounter[l] > nTimerCounter[r];
  2349. }
  2350. );
  2351. MicroProfilePrintf(CB, Handle, "\n<!--\nMarker Per Group\n");
  2352. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2353. {
  2354. uint32_t idx = nGroupCounterSort[i];
  2355. MicroProfilePrintf(CB, Handle, "%8d:%s\n", nGroupCounter[idx], S.GroupInfo[idx].pName);
  2356. }
  2357. MicroProfilePrintf(CB, Handle, "Marker Per Timer\n");
  2358. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2359. {
  2360. uint32_t idx = nTimerCounterSort[i];
  2361. MicroProfilePrintf(CB, Handle, "%8d:%s(%s)\n", nTimerCounter[idx], S.TimerInfo[idx].pName, S.GroupInfo[S.TimerInfo[idx].nGroupIndex].pName);
  2362. }
  2363. MicroProfilePrintf(CB, Handle, "\n-->\n");
  2364. S.nActiveGroup = nActiveGroup;
  2365. S.nRunning = nRunning;
  2366. #if MICROPROFILE_DEBUG
  2367. int64_t nTicksEnd = MP_TICK();
  2368. float fMs = fToMsCpu * (nTicksEnd - S.nPauseTicks);
  2369. printf("html dump took %6.2fms\n", fMs);
  2370. #endif
  2371. }
  2372. void MicroProfileWriteFile(void* Handle, size_t nSize, const char* pData)
  2373. {
  2374. fwrite(pData, nSize, 1, (FILE*)Handle);
  2375. }
  2376. void MicroProfileDumpToFile()
  2377. {
  2378. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  2379. if(S.nDumpFileNextFrame&1)
  2380. {
  2381. FILE* F = fopen(S.HtmlDumpPath, "w");
  2382. if(F)
  2383. {
  2384. MicroProfileDumpHtml(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES, S.HtmlDumpPath);
  2385. fclose(F);
  2386. }
  2387. }
  2388. if(S.nDumpFileNextFrame&2)
  2389. {
  2390. FILE* F = fopen(S.CsvDumpPath, "w");
  2391. if(F)
  2392. {
  2393. MicroProfileDumpCsv(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES);
  2394. fclose(F);
  2395. }
  2396. }
  2397. }
  2398. void MicroProfileFlushSocket(MpSocket Socket)
  2399. {
  2400. send(Socket, &S.WebServerBuffer[0], S.WebServerPut, 0);
  2401. S.WebServerPut = 0;
  2402. }
  2403. void MicroProfileWriteSocket(void* Handle, size_t nSize, const char* pData)
  2404. {
  2405. S.nWebServerDataSent += nSize;
  2406. MpSocket Socket = *(MpSocket*)Handle;
  2407. if(nSize > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE / 2)
  2408. {
  2409. MicroProfileFlushSocket(Socket);
  2410. send(Socket, pData, nSize, 0);
  2411. }
  2412. else
  2413. {
  2414. memcpy(&S.WebServerBuffer[S.WebServerPut], pData, nSize);
  2415. S.WebServerPut += nSize;
  2416. if(S.WebServerPut > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE/2)
  2417. {
  2418. MicroProfileFlushSocket(Socket);
  2419. }
  2420. }
  2421. }
  2422. #if MICROPROFILE_MINIZ
  2423. #ifndef MICROPROFILE_COMPRESS_BUFFER_SIZE
  2424. #define MICROPROFILE_COMPRESS_BUFFER_SIZE (256<<10)
  2425. #endif
  2426. #define MICROPROFILE_COMPRESS_CHUNK (MICROPROFILE_COMPRESS_BUFFER_SIZE/2)
  2427. struct MicroProfileCompressedSocketState
  2428. {
  2429. unsigned char DeflateOut[MICROPROFILE_COMPRESS_CHUNK];
  2430. unsigned char DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2431. mz_stream Stream;
  2432. MpSocket Socket;
  2433. uint32_t nSize;
  2434. uint32_t nCompressedSize;
  2435. uint32_t nFlushes;
  2436. uint32_t nMemmoveBytes;
  2437. };
  2438. void MicroProfileCompressedSocketFlush(MicroProfileCompressedSocketState* pState)
  2439. {
  2440. mz_stream& Stream = pState->Stream;
  2441. unsigned char* pSendStart = &pState->DeflateOut[0];
  2442. unsigned char* pSendEnd = &pState->DeflateOut[MICROPROFILE_COMPRESS_CHUNK - Stream.avail_out];
  2443. if(pSendStart != pSendEnd)
  2444. {
  2445. send(pState->Socket, (const char*)pSendStart, pSendEnd - pSendStart, 0);
  2446. pState->nCompressedSize += pSendEnd - pSendStart;
  2447. }
  2448. Stream.next_out = &pState->DeflateOut[0];
  2449. Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK;
  2450. }
  2451. void MicroProfileCompressedSocketStart(MicroProfileCompressedSocketState* pState, MpSocket Socket)
  2452. {
  2453. mz_stream& Stream = pState->Stream;
  2454. memset(&Stream, 0, sizeof(Stream));
  2455. Stream.next_out = &pState->DeflateOut[0];
  2456. Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK;
  2457. Stream.next_in = &pState->DeflateIn[0];
  2458. Stream.avail_in = 0;
  2459. mz_deflateInit(&Stream, Z_DEFAULT_COMPRESSION);
  2460. pState->Socket = Socket;
  2461. pState->nSize = 0;
  2462. pState->nCompressedSize = 0;
  2463. pState->nFlushes = 0;
  2464. pState->nMemmoveBytes = 0;
  2465. }
  2466. void MicroProfileCompressedSocketFinish(MicroProfileCompressedSocketState* pState)
  2467. {
  2468. mz_stream& Stream = pState->Stream;
  2469. MicroProfileCompressedSocketFlush(pState);
  2470. int r = mz_deflate(&Stream, MZ_FINISH);
  2471. MP_ASSERT(r == MZ_STREAM_END);
  2472. MicroProfileCompressedSocketFlush(pState);
  2473. r = mz_deflateEnd(&Stream);
  2474. MP_ASSERT(r == MZ_OK);
  2475. }
  2476. void MicroProfileCompressedWriteSocket(void* Handle, size_t nSize, const char* pData)
  2477. {
  2478. MicroProfileCompressedSocketState* pState = (MicroProfileCompressedSocketState*)Handle;
  2479. mz_stream& Stream = pState->Stream;
  2480. const unsigned char* pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2481. const unsigned char* pDeflateInStart = &pState->DeflateIn[0];
  2482. const unsigned char* pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2483. pState->nSize += nSize;
  2484. if(nSize <= pDeflateInRealEnd - pDeflateInEnd)
  2485. {
  2486. memcpy((void*)pDeflateInEnd, pData, nSize);
  2487. Stream.avail_in += nSize;
  2488. MP_ASSERT(Stream.next_in + Stream.avail_in <= pDeflateInRealEnd);
  2489. return;
  2490. }
  2491. int Flush = 0;
  2492. while(nSize)
  2493. {
  2494. pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2495. if(Flush)
  2496. {
  2497. pState->nFlushes++;
  2498. MicroProfileCompressedSocketFlush(pState);
  2499. pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2500. if(pDeflateInEnd == pDeflateInRealEnd)
  2501. {
  2502. if(Stream.avail_in)
  2503. {
  2504. MP_ASSERT(pDeflateInStart != Stream.next_in);
  2505. memmove((void*)pDeflateInStart, Stream.next_in, Stream.avail_in);
  2506. pState->nMemmoveBytes += Stream.avail_in;
  2507. }
  2508. Stream.next_in = pDeflateInStart;
  2509. pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2510. }
  2511. }
  2512. size_t nSpace = pDeflateInRealEnd - pDeflateInEnd;
  2513. size_t nBytes = MicroProfileMin(nSpace, nSize);
  2514. MP_ASSERT(nBytes + pDeflateInEnd <= pDeflateInRealEnd);
  2515. memcpy((void*)pDeflateInEnd, pData, nBytes);
  2516. Stream.avail_in += nBytes;
  2517. nSize -= nBytes;
  2518. pData += nBytes;
  2519. int r = mz_deflate(&Stream, MZ_NO_FLUSH);
  2520. Flush = r == MZ_BUF_ERROR || nBytes == 0 || Stream.avail_out == 0 ? 1 : 0;
  2521. MP_ASSERT(r == MZ_BUF_ERROR || r == MZ_OK);
  2522. if(r == MZ_BUF_ERROR)
  2523. {
  2524. r = mz_deflate(&Stream, MZ_SYNC_FLUSH);
  2525. }
  2526. }
  2527. }
  2528. #endif
  2529. #ifndef MicroProfileSetNonBlocking //fcntl doesnt work on a some unix like platforms..
  2530. void MicroProfileSetNonBlocking(MpSocket Socket, int NonBlocking)
  2531. {
  2532. #ifdef _WIN32
  2533. u_long nonBlocking = NonBlocking ? 1 : 0;
  2534. ioctlsocket(Socket, FIONBIO, &nonBlocking);
  2535. #else
  2536. int Options = fcntl(Socket, F_GETFL);
  2537. if(NonBlocking)
  2538. {
  2539. fcntl(Socket, F_SETFL, Options|O_NONBLOCK);
  2540. }
  2541. else
  2542. {
  2543. fcntl(Socket, F_SETFL, Options&(~O_NONBLOCK));
  2544. }
  2545. #endif
  2546. }
  2547. #endif
  2548. void MicroProfileWebServerStart()
  2549. {
  2550. #ifdef _WIN32
  2551. WSADATA wsa;
  2552. if(WSAStartup(MAKEWORD(2, 2), &wsa))
  2553. {
  2554. S.ListenerSocket = -1;
  2555. return;
  2556. }
  2557. #endif
  2558. S.ListenerSocket = socket(PF_INET, SOCK_STREAM, 6);
  2559. MP_ASSERT(!MP_INVALID_SOCKET(S.ListenerSocket));
  2560. MicroProfileSetNonBlocking(S.ListenerSocket, 1);
  2561. S.nWebServerPort = (uint32_t)-1;
  2562. struct sockaddr_in Addr;
  2563. Addr.sin_family = AF_INET;
  2564. Addr.sin_addr.s_addr = INADDR_ANY;
  2565. for(int i = 0; i < 20; ++i)
  2566. {
  2567. Addr.sin_port = htons(MICROPROFILE_WEBSERVER_PORT+i);
  2568. if(0 == bind(S.ListenerSocket, (sockaddr*)&Addr, sizeof(Addr)))
  2569. {
  2570. S.nWebServerPort = MICROPROFILE_WEBSERVER_PORT+i;
  2571. break;
  2572. }
  2573. }
  2574. listen(S.ListenerSocket, 8);
  2575. }
  2576. void MicroProfileWebServerStop()
  2577. {
  2578. #ifdef _WIN32
  2579. closesocket(S.ListenerSocket);
  2580. WSACleanup();
  2581. #else
  2582. close(S.ListenerSocket);
  2583. #endif
  2584. }
  2585. int MicroProfileParseGet(const char* pGet)
  2586. {
  2587. const char* pStart = pGet;
  2588. while(*pGet != '\0')
  2589. {
  2590. if(*pGet < '0' || *pGet > '9')
  2591. return 0;
  2592. pGet++;
  2593. }
  2594. int nFrames = atoi(pStart);
  2595. if(nFrames)
  2596. {
  2597. return nFrames;
  2598. }
  2599. else
  2600. {
  2601. return MICROPROFILE_WEBSERVER_MAXFRAMES;
  2602. }
  2603. }
  2604. bool MicroProfileWebServerUpdate()
  2605. {
  2606. MICROPROFILE_SCOPEI("MicroProfile", "Webserver-update", -1);
  2607. MpSocket Connection = accept(S.ListenerSocket, 0, 0);
  2608. bool bServed = false;
  2609. if(!MP_INVALID_SOCKET(Connection))
  2610. {
  2611. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  2612. char Req[8192];
  2613. MicroProfileSetNonBlocking(Connection, 0);
  2614. int nReceived = recv(Connection, Req, sizeof(Req)-1, 0);
  2615. if(nReceived > 0)
  2616. {
  2617. Req[nReceived] = '\0';
  2618. #if MICROPROFILE_MINIZ
  2619. #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"
  2620. #else
  2621. #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"
  2622. #endif
  2623. char* pHttp = strstr(Req, "HTTP/");
  2624. char* pGet = strstr(Req, "GET /");
  2625. char* pHost = strstr(Req, "Host: ");
  2626. auto Terminate = [](char* pString)
  2627. {
  2628. char* pEnd = pString;
  2629. while(*pEnd != '\0')
  2630. {
  2631. if(*pEnd == '\r' || *pEnd == '\n' || *pEnd == ' ')
  2632. {
  2633. *pEnd = '\0';
  2634. return;
  2635. }
  2636. pEnd++;
  2637. }
  2638. };
  2639. if(pHost)
  2640. {
  2641. pHost += sizeof("Host: ")-1;
  2642. Terminate(pHost);
  2643. }
  2644. if(pHttp && pGet)
  2645. {
  2646. *pHttp = '\0';
  2647. pGet += sizeof("GET /")-1;
  2648. Terminate(pGet);
  2649. int nFrames = MicroProfileParseGet(pGet);
  2650. if(nFrames)
  2651. {
  2652. uint64_t nTickStart = MP_TICK();
  2653. send(Connection, MICROPROFILE_HTML_HEADER, sizeof(MICROPROFILE_HTML_HEADER)-1, 0);
  2654. uint64_t nDataStart = S.nWebServerDataSent;
  2655. S.WebServerPut = 0;
  2656. #if 0 == MICROPROFILE_MINIZ
  2657. MicroProfileDumpHtml(MicroProfileWriteSocket, &Connection, nFrames, pHost);
  2658. uint64_t nDataEnd = S.nWebServerDataSent;
  2659. uint64_t nTickEnd = MP_TICK();
  2660. uint64_t nDiff = (nTickEnd - nTickStart);
  2661. float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff;
  2662. int nKb = ((nDataEnd-nDataStart)>>10) + 1;
  2663. int nCompressedKb = nKb;
  2664. MicroProfilePrintf(MicroProfileWriteSocket, &Connection, "\n<!-- Sent %dkb in %.2fms-->\n\n",nKb, fMs);
  2665. MicroProfileFlushSocket(Connection);
  2666. #else
  2667. MicroProfileCompressedSocketState CompressState;
  2668. MicroProfileCompressedSocketStart(&CompressState, Connection);
  2669. MicroProfileDumpHtml(MicroProfileCompressedWriteSocket, &CompressState, nFrames, pHost);
  2670. S.nWebServerDataSent += CompressState.nSize;
  2671. uint64_t nDataEnd = S.nWebServerDataSent;
  2672. uint64_t nTickEnd = MP_TICK();
  2673. uint64_t nDiff = (nTickEnd - nTickStart);
  2674. float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff;
  2675. int nKb = ((nDataEnd-nDataStart)>>10) + 1;
  2676. int nCompressedKb = ((CompressState.nCompressedSize)>>10) + 1;
  2677. MicroProfilePrintf(MicroProfileCompressedWriteSocket, &CompressState, "\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs);
  2678. MicroProfileCompressedSocketFinish(&CompressState);
  2679. MicroProfileFlushSocket(Connection);
  2680. #endif
  2681. #if MICROPROFILE_DEBUG
  2682. printf("\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs);
  2683. #endif
  2684. }
  2685. }
  2686. }
  2687. #ifdef _WIN32
  2688. closesocket(Connection);
  2689. #else
  2690. close(Connection);
  2691. #endif
  2692. }
  2693. return bServed;
  2694. }
  2695. #endif
  2696. #if MICROPROFILE_CONTEXT_SWITCH_TRACE
  2697. //functions that need to be implemented per platform.
  2698. void* MicroProfileTraceThread(void* unused);
  2699. bool MicroProfileIsLocalThread(uint32_t nThreadId);
  2700. void MicroProfileStartContextSwitchTrace()
  2701. {
  2702. if(!S.bContextSwitchRunning)
  2703. {
  2704. S.bContextSwitchRunning = true;
  2705. S.bContextSwitchStop = false;
  2706. MicroProfileThreadStart(&S.ContextSwitchThread, MicroProfileTraceThread);
  2707. }
  2708. }
  2709. void MicroProfileStopContextSwitchTrace()
  2710. {
  2711. if(S.bContextSwitchRunning)
  2712. {
  2713. S.bContextSwitchStop = true;
  2714. MicroProfileThreadJoin(&S.ContextSwitchThread);
  2715. }
  2716. }
  2717. #ifdef _WIN32
  2718. #define INITGUID
  2719. #include <evntrace.h>
  2720. #include <evntcons.h>
  2721. #include <strsafe.h>
  2722. static GUID g_MicroProfileThreadClassGuid = { 0x3d6fa8d1, 0xfe05, 0x11d0, 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c };
  2723. struct MicroProfileSCSwitch
  2724. {
  2725. uint32_t NewThreadId;
  2726. uint32_t OldThreadId;
  2727. int8_t NewThreadPriority;
  2728. int8_t OldThreadPriority;
  2729. uint8_t PreviousCState;
  2730. int8_t SpareByte;
  2731. int8_t OldThreadWaitReason;
  2732. int8_t OldThreadWaitMode;
  2733. int8_t OldThreadState;
  2734. int8_t OldThreadWaitIdealProcessor;
  2735. uint32_t NewThreadWaitTime;
  2736. uint32_t Reserved;
  2737. };
  2738. VOID WINAPI MicroProfileContextSwitchCallback(PEVENT_TRACE pEvent)
  2739. {
  2740. if (pEvent->Header.Guid == g_MicroProfileThreadClassGuid)
  2741. {
  2742. if (pEvent->Header.Class.Type == 36)
  2743. {
  2744. MicroProfileSCSwitch* pCSwitch = (MicroProfileSCSwitch*) pEvent->MofData;
  2745. if ((pCSwitch->NewThreadId != 0) || (pCSwitch->OldThreadId != 0))
  2746. {
  2747. MicroProfileContextSwitch Switch;
  2748. Switch.nThreadOut = pCSwitch->OldThreadId;
  2749. Switch.nThreadIn = pCSwitch->NewThreadId;
  2750. Switch.nCpu = pEvent->BufferContext.ProcessorNumber;
  2751. Switch.nTicks = pEvent->Header.TimeStamp.QuadPart;
  2752. MicroProfileContextSwitchPut(&Switch);
  2753. }
  2754. }
  2755. }
  2756. }
  2757. ULONG WINAPI MicroProfileBufferCallback(PEVENT_TRACE_LOGFILE Buffer)
  2758. {
  2759. return (S.bContextSwitchStop || !S.bContextSwitchRunning) ? FALSE : TRUE;
  2760. }
  2761. struct MicroProfileKernelTraceProperties : public EVENT_TRACE_PROPERTIES
  2762. {
  2763. char dummy[sizeof(KERNEL_LOGGER_NAME)];
  2764. };
  2765. void MicroProfileContextSwitchShutdownTrace()
  2766. {
  2767. TRACEHANDLE SessionHandle = 0;
  2768. MicroProfileKernelTraceProperties sessionProperties;
  2769. ZeroMemory(&sessionProperties, sizeof(sessionProperties));
  2770. sessionProperties.Wnode.BufferSize = sizeof(sessionProperties);
  2771. sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
  2772. sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution
  2773. sessionProperties.Wnode.Guid = SystemTraceControlGuid;
  2774. sessionProperties.BufferSize = 1;
  2775. sessionProperties.NumberOfBuffers = 128;
  2776. sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH;
  2777. sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  2778. sessionProperties.MaximumFileSize = 0;
  2779. sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
  2780. sessionProperties.LogFileNameOffset = 0;
  2781. EVENT_TRACE_LOGFILE log;
  2782. ZeroMemory(&log, sizeof(log));
  2783. log.LoggerName = KERNEL_LOGGER_NAME;
  2784. log.ProcessTraceMode = 0;
  2785. TRACEHANDLE hLog = OpenTrace(&log);
  2786. if (hLog)
  2787. {
  2788. ControlTrace(SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties, EVENT_TRACE_CONTROL_STOP);
  2789. }
  2790. CloseTrace(hLog);
  2791. }
  2792. void* MicroProfileTraceThread(void* unused)
  2793. {
  2794. MicroProfileContextSwitchShutdownTrace();
  2795. ULONG status = ERROR_SUCCESS;
  2796. TRACEHANDLE SessionHandle = 0;
  2797. MicroProfileKernelTraceProperties sessionProperties;
  2798. ZeroMemory(&sessionProperties, sizeof(sessionProperties));
  2799. sessionProperties.Wnode.BufferSize = sizeof(sessionProperties);
  2800. sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
  2801. sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution
  2802. sessionProperties.Wnode.Guid = SystemTraceControlGuid;
  2803. sessionProperties.BufferSize = 1;
  2804. sessionProperties.NumberOfBuffers = 128;
  2805. sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH|EVENT_TRACE_FLAG_PROCESS;
  2806. sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  2807. sessionProperties.MaximumFileSize = 0;
  2808. sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
  2809. sessionProperties.LogFileNameOffset = 0;
  2810. status = StartTrace((PTRACEHANDLE) &SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties);
  2811. if (ERROR_SUCCESS != status)
  2812. {
  2813. S.bContextSwitchRunning = false;
  2814. return 0;
  2815. }
  2816. EVENT_TRACE_LOGFILE log;
  2817. ZeroMemory(&log, sizeof(log));
  2818. log.LoggerName = KERNEL_LOGGER_NAME;
  2819. log.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_RAW_TIMESTAMP;
  2820. log.EventCallback = MicroProfileContextSwitchCallback;
  2821. log.BufferCallback = MicroProfileBufferCallback;
  2822. TRACEHANDLE hLog = OpenTrace(&log);
  2823. ProcessTrace(&hLog, 1, 0, 0);
  2824. CloseTrace(hLog);
  2825. MicroProfileContextSwitchShutdownTrace();
  2826. S.bContextSwitchRunning = false;
  2827. return 0;
  2828. }
  2829. bool MicroProfileIsLocalThread(uint32_t nThreadId)
  2830. {
  2831. HANDLE h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, nThreadId);
  2832. if(h == NULL)
  2833. return false;
  2834. DWORD hProcess = GetProcessIdOfThread(h);
  2835. CloseHandle(h);
  2836. return GetCurrentProcessId() == hProcess;
  2837. }
  2838. #elif defined(__APPLE__)
  2839. #include <sys/time.h>
  2840. void* MicroProfileTraceThread(void* unused)
  2841. {
  2842. FILE* pFile = fopen("mypipe", "r");
  2843. if(!pFile)
  2844. {
  2845. printf("CONTEXT SWITCH FAILED TO OPEN FILE: make sure to run dtrace script\n");
  2846. S.bContextSwitchRunning = false;
  2847. return 0;
  2848. }
  2849. printf("STARTING TRACE THREAD\n");
  2850. char* pLine = 0;
  2851. size_t cap = 0;
  2852. size_t len = 0;
  2853. struct timeval tv;
  2854. gettimeofday(&tv, NULL);
  2855. uint64_t nsSinceEpoch = ((uint64_t)(tv.tv_sec) * 1000000 + (uint64_t)(tv.tv_usec)) * 1000;
  2856. uint64_t nTickEpoch = MP_TICK();
  2857. uint32_t nLastThread[MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS] = {0};
  2858. mach_timebase_info_data_t sTimebaseInfo;
  2859. mach_timebase_info(&sTimebaseInfo);
  2860. S.bContextSwitchRunning = true;
  2861. uint64_t nProcessed = 0;
  2862. uint64_t nProcessedLast = 0;
  2863. while((len = getline(&pLine, &cap, pFile))>0 && !S.bContextSwitchStop)
  2864. {
  2865. nProcessed += len;
  2866. if(nProcessed - nProcessedLast > 10<<10)
  2867. {
  2868. nProcessedLast = nProcessed;
  2869. printf("processed %llukb %llukb\n", (nProcessed-nProcessedLast)>>10,nProcessed >>10);
  2870. }
  2871. char* pX = strchr(pLine, 'X');
  2872. if(pX)
  2873. {
  2874. int cpu = atoi(pX+1);
  2875. char* pX2 = strchr(pX + 1, 'X');
  2876. char* pX3 = strchr(pX2 + 1, 'X');
  2877. int thread = atoi(pX2+1);
  2878. char* lala;
  2879. int64_t timestamp = strtoll(pX3 + 1, &lala, 10);
  2880. MicroProfileContextSwitch Switch;
  2881. //convert to ticks.
  2882. uint64_t nDeltaNsSinceEpoch = timestamp - nsSinceEpoch;
  2883. uint64_t nDeltaTickSinceEpoch = sTimebaseInfo.numer * nDeltaNsSinceEpoch / sTimebaseInfo.denom;
  2884. uint64_t nTicks = nDeltaTickSinceEpoch + nTickEpoch;
  2885. if(cpu < MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS)
  2886. {
  2887. Switch.nThreadOut = nLastThread[cpu];
  2888. Switch.nThreadIn = thread;
  2889. nLastThread[cpu] = thread;
  2890. Switch.nCpu = cpu;
  2891. Switch.nTicks = nTicks;
  2892. MicroProfileContextSwitchPut(&Switch);
  2893. }
  2894. }
  2895. }
  2896. printf("EXITING TRACE THREAD\n");
  2897. S.bContextSwitchRunning = false;
  2898. return 0;
  2899. }
  2900. bool MicroProfileIsLocalThread(uint32_t nThreadId)
  2901. {
  2902. return false;
  2903. }
  2904. #endif
  2905. #else
  2906. bool MicroProfileIsLocalThread(uint32_t nThreadId){return false;}
  2907. void MicroProfileStopContextSwitchTrace(){}
  2908. void MicroProfileStartContextSwitchTrace(){}
  2909. #endif
  2910. #if MICROPROFILE_GPU_TIMERS_D3D11
  2911. uint32_t MicroProfileGpuInsertTimeStamp()
  2912. {
  2913. MicroProfileD3D11Frame& Frame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame];
  2914. if(Frame.m_nRateQueryStarted)
  2915. {
  2916. uint32_t nCurrent = (Frame.m_nQueryStart + Frame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES;
  2917. uint32_t nNext = (nCurrent + 1) % MICROPROFILE_D3D_MAX_QUERIES;
  2918. if(nNext != S.GPU.m_nQueryGet)
  2919. {
  2920. Frame.m_nQueryCount++;
  2921. ID3D11Query* pQuery = (ID3D11Query*)S.GPU.m_pQueries[nCurrent];
  2922. ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext;
  2923. pContext->End(pQuery);
  2924. S.GPU.m_nQueryPut = nNext;
  2925. return nCurrent;
  2926. }
  2927. }
  2928. return (uint32_t)-1;
  2929. }
  2930. uint64_t MicroProfileGpuGetTimeStamp(uint32_t nIndex)
  2931. {
  2932. if(nIndex == (uint32_t)-1)
  2933. {
  2934. return (uint64_t)-1;
  2935. }
  2936. int64_t nResult = S.GPU.m_nQueryResults[nIndex];
  2937. MP_ASSERT(nResult != -1);
  2938. return nResult;
  2939. }
  2940. bool MicroProfileGpuGetData(void* pQuery, void* pData, uint32_t nDataSize)
  2941. {
  2942. HRESULT hr;
  2943. do
  2944. {
  2945. hr = ((ID3D11DeviceContext*)S.GPU.m_pDeviceContext)->GetData((ID3D11Query*)pQuery, pData, nDataSize, 0);
  2946. }while(hr == S_FALSE);
  2947. switch(hr)
  2948. {
  2949. case DXGI_ERROR_DEVICE_REMOVED:
  2950. case DXGI_ERROR_INVALID_CALL:
  2951. case E_INVALIDARG:
  2952. MP_BREAK();
  2953. return false;
  2954. }
  2955. return true;
  2956. }
  2957. uint64_t MicroProfileTicksPerSecondGpu()
  2958. {
  2959. return S.GPU.m_nQueryFrequency;
  2960. }
  2961. void MicroProfileGpuFlip()
  2962. {
  2963. MicroProfileD3D11Frame& CurrentFrame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame];
  2964. ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext;
  2965. if(CurrentFrame.m_nRateQueryStarted)
  2966. {
  2967. pContext->End((ID3D11Query*)CurrentFrame.m_pRateQuery);
  2968. }
  2969. uint32_t nNextFrame = (S.GPU.m_nQueryFrame + 1) % MICROPROFILE_GPU_FRAME_DELAY;
  2970. MicroProfileD3D11Frame& OldFrame = S.GPU.m_QueryFrames[nNextFrame];
  2971. if(OldFrame.m_nRateQueryStarted)
  2972. {
  2973. struct RateQueryResult
  2974. {
  2975. uint64_t nFrequency;
  2976. BOOL bDisjoint;
  2977. };
  2978. RateQueryResult Result;
  2979. if(MicroProfileGpuGetData(OldFrame.m_pRateQuery, &Result, sizeof(Result)))
  2980. {
  2981. if(S.GPU.m_nQueryFrequency != (int64_t)Result.nFrequency)
  2982. {
  2983. if(S.GPU.m_nQueryFrequency)
  2984. {
  2985. OutputDebugString("Query freq changing");
  2986. }
  2987. S.GPU.m_nQueryFrequency = Result.nFrequency;
  2988. }
  2989. uint32_t nStart = OldFrame.m_nQueryStart;
  2990. uint32_t nCount = OldFrame.m_nQueryCount;
  2991. for(uint32_t i = 0; i < nCount; ++i)
  2992. {
  2993. uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES;
  2994. if(!MicroProfileGpuGetData(S.GPU.m_pQueries[nIndex], &S.GPU.m_nQueryResults[nIndex], sizeof(uint64_t)))
  2995. {
  2996. S.GPU.m_nQueryResults[nIndex] = -1;
  2997. }
  2998. }
  2999. }
  3000. else
  3001. {
  3002. uint32_t nStart = OldFrame.m_nQueryStart;
  3003. uint32_t nCount = OldFrame.m_nQueryCount;
  3004. for(uint32_t i = 0; i < nCount; ++i)
  3005. {
  3006. uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES;
  3007. S.GPU.m_nQueryResults[nIndex] = -1;
  3008. }
  3009. }
  3010. S.GPU.m_nQueryGet = (OldFrame.m_nQueryStart + OldFrame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES;
  3011. }
  3012. S.GPU.m_nQueryFrame = nNextFrame;
  3013. MicroProfileD3D11Frame& NextFrame = S.GPU.m_QueryFrames[nNextFrame];
  3014. pContext->Begin((ID3D11Query*)NextFrame.m_pRateQuery);
  3015. NextFrame.m_nQueryStart = S.GPU.m_nQueryPut;
  3016. NextFrame.m_nQueryCount = 0;
  3017. NextFrame.m_nRateQueryStarted = 1;
  3018. }
  3019. void MicroProfileGpuInitD3D11(void* pDevice_, void* pDeviceContext_)
  3020. {
  3021. ID3D11Device* pDevice = (ID3D11Device*)pDevice_;
  3022. ID3D11DeviceContext* pDeviceContext = (ID3D11DeviceContext*)pDeviceContext_;
  3023. S.GPU.m_pDeviceContext = pDeviceContext_;
  3024. D3D11_QUERY_DESC Desc;
  3025. Desc.MiscFlags = 0;
  3026. Desc.Query = D3D11_QUERY_TIMESTAMP;
  3027. for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i)
  3028. {
  3029. HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_pQueries[i]);
  3030. MP_ASSERT(hr == S_OK);
  3031. S.GPU.m_nQueryResults[i] = -1;
  3032. }
  3033. S.GPU.m_nQueryPut = 0;
  3034. S.GPU.m_nQueryGet = 0;
  3035. S.GPU.m_nQueryFrame = 0;
  3036. S.GPU.m_nQueryFrequency = 0;
  3037. Desc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
  3038. for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i)
  3039. {
  3040. S.GPU.m_QueryFrames[i].m_nQueryStart = 0;
  3041. S.GPU.m_QueryFrames[i].m_nQueryCount = 0;
  3042. S.GPU.m_QueryFrames[i].m_nRateQueryStarted = 0;
  3043. HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_QueryFrames[i].m_pRateQuery);
  3044. MP_ASSERT(hr == S_OK);
  3045. }
  3046. }
  3047. void MicroProfileGpuShutdown()
  3048. {
  3049. for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i)
  3050. {
  3051. ((ID3D11Query*)&S.GPU.m_pQueries[i])->Release();
  3052. S.GPU.m_pQueries[i] = 0;
  3053. }
  3054. for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i)
  3055. {
  3056. ((ID3D11Query*)S.GPU.m_QueryFrames[i].m_pRateQuery)->Release();
  3057. S.GPU.m_QueryFrames[i].m_pRateQuery = 0;
  3058. }
  3059. }
  3060. int MicroProfileGetGpuTickReference(int64_t* pOutCPU, int64_t* pOutGpu)
  3061. {
  3062. return 0;
  3063. }
  3064. #elif MICROPROFILE_GPU_TIMERS_GL
  3065. void MicroProfileGpuInitGL()
  3066. {
  3067. S.GPU.GLTimerPos = 0;
  3068. glGenQueries(MICROPROFILE_GL_MAX_QUERIES, &S.GPU.GLTimers[0]);
  3069. }
  3070. uint32_t MicroProfileGpuInsertTimeStamp()
  3071. {
  3072. uint32_t nIndex = (S.GPU.GLTimerPos+1)%MICROPROFILE_GL_MAX_QUERIES;
  3073. glQueryCounter(S.GPU.GLTimers[nIndex], GL_TIMESTAMP);
  3074. S.GPU.GLTimerPos = nIndex;
  3075. return nIndex;
  3076. }
  3077. uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey)
  3078. {
  3079. uint64_t result;
  3080. glGetQueryObjectui64v(S.GPU.GLTimers[nKey], GL_QUERY_RESULT, &result);
  3081. return result;
  3082. }
  3083. uint64_t MicroProfileTicksPerSecondGpu()
  3084. {
  3085. return 1000000000ll;
  3086. }
  3087. int MicroProfileGetGpuTickReference(int64_t* pOutCpu, int64_t* pOutGpu)
  3088. {
  3089. int64_t nGpuTimeStamp;
  3090. glGetInteger64v(GL_TIMESTAMP, &nGpuTimeStamp);
  3091. if(nGpuTimeStamp)
  3092. {
  3093. *pOutCpu = MP_TICK();
  3094. *pOutGpu = nGpuTimeStamp;
  3095. #if 0 //debug test if timestamp diverges
  3096. static int64_t nTicksPerSecondCpu = MicroProfileTicksPerSecondCpu();
  3097. static int64_t nTicksPerSecondGpu = MicroProfileTicksPerSecondGpu();
  3098. static int64_t nGpuStart = 0;
  3099. static int64_t nCpuStart = 0;
  3100. if(!nCpuStart)
  3101. {
  3102. nCpuStart = *pOutCpu;
  3103. nGpuStart = *pOutGpu;
  3104. }
  3105. static int nCountDown = 100;
  3106. if(0 == nCountDown--)
  3107. {
  3108. int64_t nCurCpu = *pOutCpu;
  3109. int64_t nCurGpu = *pOutGpu;
  3110. double fDistanceCpu = (nCurCpu - nCpuStart) / (double)nTicksPerSecondCpu;
  3111. double fDistanceGpu = (nCurGpu - nGpuStart) / (double)nTicksPerSecondGpu;
  3112. char buf[254];
  3113. snprintf(buf, sizeof(buf)-1,"Distance %f %f diff %f\n", fDistanceCpu, fDistanceGpu, fDistanceCpu-fDistanceGpu);
  3114. OutputDebugString(buf);
  3115. nCountDown = 100;
  3116. }
  3117. #endif
  3118. return 1;
  3119. }
  3120. return 0;
  3121. }
  3122. #endif
  3123. #undef S
  3124. #ifdef _WIN32
  3125. #pragma warning(pop)
  3126. #endif
  3127. #endif
  3128. #endif
  3129. #ifdef MICROPROFILE_EMBED_HTML
  3130. #include "microprofile_html.h"
  3131. #endif