microprofile.h 121 KB

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