microprofile.h 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604
  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. // To avoid crashing due to OOB memory accesses/asserts
  1459. // simply skip this iteration
  1460. // MP_ASSERT(nStackPos < MICROPROFILE_STACK_MAX);
  1461. if (nStackPos >= MICROPROFILE_STACK_MAX) {
  1462. break;
  1463. }
  1464. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1465. pGroupStackPos[nGroup]++;
  1466. pStack[nStackPos++] = k;
  1467. pChildTickStack[nStackPos] = 0;
  1468. }
  1469. else if(MP_LOG_META == nType)
  1470. {
  1471. if(nStackPos)
  1472. {
  1473. int64_t nMetaIndex = MicroProfileLogTimerIndex(LE);
  1474. int64_t nMetaCount = MicroProfileLogGetTick(LE);
  1475. MP_ASSERT(nMetaIndex < MICROPROFILE_META_MAX);
  1476. int64_t nCounter = MicroProfileLogTimerIndex(pLog->Log[pStack[nStackPos-1]]);
  1477. S.MetaCounters[nMetaIndex].nCounters[nCounter] += nMetaCount;
  1478. }
  1479. }
  1480. else if(MP_LOG_LEAVE == nType)
  1481. {
  1482. int nTimer = MicroProfileLogTimerIndex(LE);
  1483. uint8_t nGroup = pTimerToGroup[nTimer];
  1484. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1485. if(nStackPos)
  1486. {
  1487. int64_t nTickStart = pLog->Log[pStack[nStackPos-1]];
  1488. int64_t nTicks = MicroProfileLogTickDifference(nTickStart, LE);
  1489. int64_t nChildTicks = pChildTickStack[nStackPos];
  1490. nStackPos--;
  1491. pChildTickStack[nStackPos] += nTicks;
  1492. uint32_t nTimerIndex = MicroProfileLogTimerIndex(LE);
  1493. S.Frame[nTimerIndex].nTicks += nTicks;
  1494. S.FrameExclusive[nTimerIndex] += (nTicks-nChildTicks);
  1495. S.Frame[nTimerIndex].nCount += 1;
  1496. MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS);
  1497. uint8_t nGroupStackPos = pGroupStackPos[nGroup];
  1498. if(nGroupStackPos)
  1499. {
  1500. nGroupStackPos--;
  1501. if(0 == nGroupStackPos)
  1502. {
  1503. nGroupTicks[nGroup] += nTicks;
  1504. }
  1505. pGroupStackPos[nGroup] = nGroupStackPos;
  1506. }
  1507. }
  1508. }
  1509. }
  1510. }
  1511. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1512. {
  1513. pLog->nGroupTicks[j] += nGroupTicks[j];
  1514. pFrameGroup[j] += nGroupTicks[j];
  1515. }
  1516. pLog->nStackPos = nStackPos;
  1517. }
  1518. }
  1519. {
  1520. MICROPROFILE_SCOPE(g_MicroProfileAccumulate);
  1521. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1522. {
  1523. S.AccumTimers[i].nTicks += S.Frame[i].nTicks;
  1524. S.AccumTimers[i].nCount += S.Frame[i].nCount;
  1525. S.AccumMaxTimers[i] = MicroProfileMax(S.AccumMaxTimers[i], S.Frame[i].nTicks);
  1526. S.AccumTimersExclusive[i] += S.FrameExclusive[i];
  1527. S.AccumMaxTimersExclusive[i] = MicroProfileMax(S.AccumMaxTimersExclusive[i], S.FrameExclusive[i]);
  1528. }
  1529. for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i)
  1530. {
  1531. S.AccumGroup[i] += pFrameGroup[i];
  1532. S.AccumGroupMax[i] = MicroProfileMax(S.AccumGroupMax[i], pFrameGroup[i]);
  1533. }
  1534. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1535. {
  1536. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1537. {
  1538. auto& Meta = S.MetaCounters[j];
  1539. uint64_t nSum = 0;;
  1540. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1541. {
  1542. uint64_t nCounter = Meta.nCounters[i];
  1543. Meta.nAccumMax[i] = MicroProfileMax(Meta.nAccumMax[i], nCounter);
  1544. Meta.nAccum[i] += nCounter;
  1545. nSum += nCounter;
  1546. }
  1547. Meta.nSumAccum += nSum;
  1548. Meta.nSumAccumMax = MicroProfileMax(Meta.nSumAccumMax, nSum);
  1549. }
  1550. }
  1551. }
  1552. for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i)
  1553. {
  1554. if(S.Graph[i].nToken != MICROPROFILE_INVALID_TOKEN)
  1555. {
  1556. MicroProfileToken nToken = S.Graph[i].nToken;
  1557. S.Graph[i].nHistory[S.nGraphPut] = S.Frame[MicroProfileGetTimerIndex(nToken)].nTicks;
  1558. }
  1559. }
  1560. S.nGraphPut = (S.nGraphPut+1) % MICROPROFILE_GRAPH_HISTORY;
  1561. }
  1562. if(S.nRunning && S.nAggregateFlip <= ++S.nAggregateFlipCount)
  1563. {
  1564. nAggregateFlip = 1;
  1565. if(S.nAggregateFlip) // if 0 accumulate indefinitely
  1566. {
  1567. nAggregateClear = 1;
  1568. }
  1569. }
  1570. }
  1571. if(nAggregateFlip)
  1572. {
  1573. memcpy(&S.Aggregate[0], &S.AccumTimers[0], sizeof(S.Aggregate[0]) * S.nTotalTimers);
  1574. memcpy(&S.AggregateMax[0], &S.AccumMaxTimers[0], sizeof(S.AggregateMax[0]) * S.nTotalTimers);
  1575. memcpy(&S.AggregateExclusive[0], &S.AccumTimersExclusive[0], sizeof(S.AggregateExclusive[0]) * S.nTotalTimers);
  1576. memcpy(&S.AggregateMaxExclusive[0], &S.AccumMaxTimersExclusive[0], sizeof(S.AggregateMaxExclusive[0]) * S.nTotalTimers);
  1577. memcpy(&S.AggregateGroup[0], &S.AccumGroup[0], sizeof(S.AggregateGroup));
  1578. memcpy(&S.AggregateGroupMax[0], &S.AccumGroupMax[0], sizeof(S.AggregateGroup));
  1579. for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i)
  1580. {
  1581. MicroProfileThreadLog* pLog = S.Pool[i];
  1582. if(!pLog)
  1583. continue;
  1584. memcpy(&pLog->nAggregateGroupTicks[0], &pLog->nGroupTicks[0], sizeof(pLog->nAggregateGroupTicks));
  1585. if(nAggregateClear)
  1586. {
  1587. memset(&pLog->nGroupTicks[0], 0, sizeof(pLog->nGroupTicks));
  1588. }
  1589. }
  1590. for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j)
  1591. {
  1592. if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j)))
  1593. {
  1594. auto& Meta = S.MetaCounters[j];
  1595. memcpy(&Meta.nAggregateMax[0], &Meta.nAccumMax[0], sizeof(Meta.nAggregateMax[0]) * S.nTotalTimers);
  1596. memcpy(&Meta.nAggregate[0], &Meta.nAccum[0], sizeof(Meta.nAggregate[0]) * S.nTotalTimers);
  1597. Meta.nSumAggregate = Meta.nSumAccum;
  1598. Meta.nSumAggregateMax = Meta.nSumAccumMax;
  1599. if(nAggregateClear)
  1600. {
  1601. memset(&Meta.nAccumMax[0], 0, sizeof(Meta.nAccumMax[0]) * S.nTotalTimers);
  1602. memset(&Meta.nAccum[0], 0, sizeof(Meta.nAccum[0]) * S.nTotalTimers);
  1603. Meta.nSumAccum = 0;
  1604. Meta.nSumAccumMax = 0;
  1605. }
  1606. }
  1607. }
  1608. S.nAggregateFrames = S.nAggregateFlipCount;
  1609. S.nFlipAggregateDisplay = S.nFlipAggregate;
  1610. S.nFlipMaxDisplay = S.nFlipMax;
  1611. if(nAggregateClear)
  1612. {
  1613. memset(&S.AccumTimers[0], 0, sizeof(S.Aggregate[0]) * S.nTotalTimers);
  1614. memset(&S.AccumMaxTimers[0], 0, sizeof(S.AccumMaxTimers[0]) * S.nTotalTimers);
  1615. memset(&S.AccumTimersExclusive[0], 0, sizeof(S.AggregateExclusive[0]) * S.nTotalTimers);
  1616. memset(&S.AccumMaxTimersExclusive[0], 0, sizeof(S.AccumMaxTimersExclusive[0]) * S.nTotalTimers);
  1617. memset(&S.AccumGroup[0], 0, sizeof(S.AggregateGroup));
  1618. memset(&S.AccumGroupMax[0], 0, sizeof(S.AggregateGroup));
  1619. S.nAggregateFlipCount = 0;
  1620. S.nFlipAggregate = 0;
  1621. S.nFlipMax = 0;
  1622. S.nAggregateFlipTick = MP_TICK();
  1623. }
  1624. }
  1625. S.nAggregateClear = 0;
  1626. uint64_t nNewActiveGroup = 0;
  1627. if(S.nForceEnable || (S.nDisplay && S.nRunning))
  1628. nNewActiveGroup = S.nAllGroupsWanted ? S.nGroupMask : S.nActiveGroupWanted;
  1629. nNewActiveGroup |= S.nForceGroup;
  1630. nNewActiveGroup |= S.nForceGroupUI;
  1631. if(S.nActiveGroup != nNewActiveGroup)
  1632. S.nActiveGroup = nNewActiveGroup;
  1633. uint32_t nNewActiveBars = 0;
  1634. if(S.nDisplay && S.nRunning)
  1635. nNewActiveBars = S.nBars;
  1636. if(S.nForceMetaCounters)
  1637. {
  1638. for(int i = 0; i < MICROPROFILE_META_MAX; ++i)
  1639. {
  1640. if(S.MetaCounters[i].pName)
  1641. {
  1642. nNewActiveBars |= (MP_DRAW_META_FIRST<<i);
  1643. }
  1644. }
  1645. }
  1646. if(nNewActiveBars != S.nActiveBars)
  1647. S.nActiveBars = nNewActiveBars;
  1648. }
  1649. void MicroProfileSetForceEnable(bool bEnable)
  1650. {
  1651. S.nForceEnable = bEnable ? 1 : 0;
  1652. }
  1653. bool MicroProfileGetForceEnable()
  1654. {
  1655. return S.nForceEnable != 0;
  1656. }
  1657. void MicroProfileSetEnableAllGroups(bool bEnableAllGroups)
  1658. {
  1659. S.nAllGroupsWanted = bEnableAllGroups ? 1 : 0;
  1660. }
  1661. inline void MicroProfileEnableCategory(const char* pCategory, bool bEnabled)
  1662. {
  1663. int nCategoryIndex = -1;
  1664. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  1665. {
  1666. if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName))
  1667. {
  1668. nCategoryIndex = (int)i;
  1669. break;
  1670. }
  1671. }
  1672. if(nCategoryIndex >= 0)
  1673. {
  1674. if(bEnabled)
  1675. {
  1676. S.nActiveGroupWanted |= S.CategoryInfo[nCategoryIndex].nGroupMask;
  1677. }
  1678. else
  1679. {
  1680. S.nActiveGroupWanted &= ~S.CategoryInfo[nCategoryIndex].nGroupMask;
  1681. }
  1682. }
  1683. }
  1684. void MicroProfileEnableCategory(const char* pCategory)
  1685. {
  1686. MicroProfileEnableCategory(pCategory, true);
  1687. }
  1688. void MicroProfileDisableCategory(const char* pCategory)
  1689. {
  1690. MicroProfileEnableCategory(pCategory, false);
  1691. }
  1692. bool MicroProfileGetEnableAllGroups()
  1693. {
  1694. return 0 != S.nAllGroupsWanted;
  1695. }
  1696. void MicroProfileSetForceMetaCounters(bool bForce)
  1697. {
  1698. S.nForceMetaCounters = bForce ? 1 : 0;
  1699. }
  1700. bool MicroProfileGetForceMetaCounters()
  1701. {
  1702. return 0 != S.nForceMetaCounters;
  1703. }
  1704. void MicroProfileEnableMetaCounter(const char* pMeta)
  1705. {
  1706. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1707. {
  1708. if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta))
  1709. {
  1710. S.nBars |= (MP_DRAW_META_FIRST<<i);
  1711. return;
  1712. }
  1713. }
  1714. }
  1715. void MicroProfileDisableMetaCounter(const char* pMeta)
  1716. {
  1717. for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i)
  1718. {
  1719. if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta))
  1720. {
  1721. S.nBars &= ~(MP_DRAW_META_FIRST<<i);
  1722. return;
  1723. }
  1724. }
  1725. }
  1726. void MicroProfileSetAggregateFrames(int nFrames)
  1727. {
  1728. S.nAggregateFlip = (uint32_t)nFrames;
  1729. if(0 == nFrames)
  1730. {
  1731. S.nAggregateClear = 1;
  1732. }
  1733. }
  1734. int MicroProfileGetAggregateFrames()
  1735. {
  1736. return S.nAggregateFlip;
  1737. }
  1738. int MicroProfileGetCurrentAggregateFrames()
  1739. {
  1740. return int(S.nAggregateFlip ? S.nAggregateFlip : S.nAggregateFlipCount);
  1741. }
  1742. void MicroProfileForceEnableGroup(const char* pGroup, MicroProfileTokenType Type)
  1743. {
  1744. MicroProfileInit();
  1745. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1746. uint16_t nGroup = MicroProfileGetGroup(pGroup, Type);
  1747. S.nForceGroup |= (1ll << nGroup);
  1748. }
  1749. void MicroProfileForceDisableGroup(const char* pGroup, MicroProfileTokenType Type)
  1750. {
  1751. MicroProfileInit();
  1752. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  1753. uint16_t nGroup = MicroProfileGetGroup(pGroup, Type);
  1754. S.nForceGroup &= ~(1ll << nGroup);
  1755. }
  1756. inline void MicroProfileCalcAllTimers(float* pTimers, float* pAverage, float* pMax, float* pCallAverage, float* pExclusive, float* pAverageExclusive, float* pMaxExclusive, float* pTotal, uint32_t nSize)
  1757. {
  1758. for(uint32_t i = 0; i < S.nTotalTimers && i < nSize; ++i)
  1759. {
  1760. const uint32_t nGroupId = S.TimerInfo[i].nGroupIndex;
  1761. const float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupId].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu());
  1762. uint32_t nTimer = i;
  1763. uint32_t nIdx = i * 2;
  1764. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  1765. uint32_t nAggregateCount = S.Aggregate[nTimer].nCount ? S.Aggregate[nTimer].nCount : 1;
  1766. float fToPrc = S.fRcpReferenceTime;
  1767. float fMs = fToMs * (S.Frame[nTimer].nTicks);
  1768. float fPrc = MicroProfileMin(fMs * fToPrc, 1.f);
  1769. float fAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateFrames);
  1770. float fAveragePrc = MicroProfileMin(fAverageMs * fToPrc, 1.f);
  1771. float fMaxMs = fToMs * (S.AggregateMax[nTimer]);
  1772. float fMaxPrc = MicroProfileMin(fMaxMs * fToPrc, 1.f);
  1773. float fCallAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateCount);
  1774. float fCallAveragePrc = MicroProfileMin(fCallAverageMs * fToPrc, 1.f);
  1775. float fMsExclusive = fToMs * (S.FrameExclusive[nTimer]);
  1776. float fPrcExclusive = MicroProfileMin(fMsExclusive * fToPrc, 1.f);
  1777. float fAverageMsExclusive = fToMs * (S.AggregateExclusive[nTimer] / nAggregateFrames);
  1778. float fAveragePrcExclusive = MicroProfileMin(fAverageMsExclusive * fToPrc, 1.f);
  1779. float fMaxMsExclusive = fToMs * (S.AggregateMaxExclusive[nTimer]);
  1780. float fMaxPrcExclusive = MicroProfileMin(fMaxMsExclusive * fToPrc, 1.f);
  1781. float fTotalMs = fToMs * S.Aggregate[nTimer].nTicks;
  1782. pTimers[nIdx] = fMs;
  1783. pTimers[nIdx+1] = fPrc;
  1784. pAverage[nIdx] = fAverageMs;
  1785. pAverage[nIdx+1] = fAveragePrc;
  1786. pMax[nIdx] = fMaxMs;
  1787. pMax[nIdx+1] = fMaxPrc;
  1788. pCallAverage[nIdx] = fCallAverageMs;
  1789. pCallAverage[nIdx+1] = fCallAveragePrc;
  1790. pExclusive[nIdx] = fMsExclusive;
  1791. pExclusive[nIdx+1] = fPrcExclusive;
  1792. pAverageExclusive[nIdx] = fAverageMsExclusive;
  1793. pAverageExclusive[nIdx+1] = fAveragePrcExclusive;
  1794. pMaxExclusive[nIdx] = fMaxMsExclusive;
  1795. pMaxExclusive[nIdx+1] = fMaxPrcExclusive;
  1796. pTotal[nIdx] = fTotalMs;
  1797. pTotal[nIdx+1] = 0.f;
  1798. }
  1799. }
  1800. void MicroProfileTogglePause()
  1801. {
  1802. S.nToggleRunning = 1;
  1803. }
  1804. float MicroProfileGetTime(const char* pGroup, const char* pName)
  1805. {
  1806. MicroProfileToken nToken = MicroProfileFindToken(pGroup, pName);
  1807. if(nToken == MICROPROFILE_INVALID_TOKEN)
  1808. {
  1809. return 0.f;
  1810. }
  1811. uint32_t nTimerIndex = MicroProfileGetTimerIndex(nToken);
  1812. uint32_t nGroupIndex = MicroProfileGetGroupIndex(nToken);
  1813. float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupIndex].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu());
  1814. return S.Frame[nTimerIndex].nTicks * fToMs;
  1815. }
  1816. void MicroProfileContextSwitchSearch(uint32_t* pContextSwitchStart, uint32_t* pContextSwitchEnd, uint64_t nBaseTicksCpu, uint64_t nBaseTicksEndCpu)
  1817. {
  1818. MICROPROFILE_SCOPE(g_MicroProfileContextSwitchSearch);
  1819. uint32_t nContextSwitchPut = S.nContextSwitchPut;
  1820. uint64_t nContextSwitchStart, nContextSwitchEnd;
  1821. nContextSwitchStart = nContextSwitchEnd = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - 1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1822. int64_t nSearchEnd = nBaseTicksEndCpu + MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu());
  1823. int64_t nSearchBegin = nBaseTicksCpu - MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu());
  1824. for(uint32_t i = 0; i < MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; ++i)
  1825. {
  1826. uint32_t nIndex = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - (i+1)) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE;
  1827. MicroProfileContextSwitch& CS = S.ContextSwitch[nIndex];
  1828. if(CS.nTicks > nSearchEnd)
  1829. {
  1830. nContextSwitchEnd = nIndex;
  1831. }
  1832. if(CS.nTicks > nSearchBegin)
  1833. {
  1834. nContextSwitchStart = nIndex;
  1835. }
  1836. }
  1837. *pContextSwitchStart = nContextSwitchStart;
  1838. *pContextSwitchEnd = nContextSwitchEnd;
  1839. }
  1840. #if MICROPROFILE_WEBSERVER
  1841. #define MICROPROFILE_EMBED_HTML
  1842. extern const char* g_MicroProfileHtml_begin[];
  1843. extern size_t g_MicroProfileHtml_begin_sizes[];
  1844. extern size_t g_MicroProfileHtml_begin_count;
  1845. extern const char* g_MicroProfileHtml_end[];
  1846. extern size_t g_MicroProfileHtml_end_sizes[];
  1847. extern size_t g_MicroProfileHtml_end_count;
  1848. typedef void MicroProfileWriteCallback(void* Handle, size_t size, const char* pData);
  1849. uint32_t MicroProfileWebServerPort()
  1850. {
  1851. return S.nWebServerPort;
  1852. }
  1853. void MicroProfileDumpFile(const char* pHtml, const char* pCsv)
  1854. {
  1855. S.nDumpFileNextFrame = 0;
  1856. if(pHtml)
  1857. {
  1858. uint32_t nLen = strlen(pHtml);
  1859. if(nLen > sizeof(S.HtmlDumpPath)-1)
  1860. {
  1861. return;
  1862. }
  1863. memcpy(S.HtmlDumpPath, pHtml, nLen+1);
  1864. S.nDumpFileNextFrame |= 1;
  1865. }
  1866. if(pCsv)
  1867. {
  1868. uint32_t nLen = strlen(pCsv);
  1869. if(nLen > sizeof(S.CsvDumpPath)-1)
  1870. {
  1871. return;
  1872. }
  1873. memcpy(S.CsvDumpPath, pCsv, nLen+1);
  1874. S.nDumpFileNextFrame |= 2;
  1875. }
  1876. }
  1877. void MicroProfilePrintf(MicroProfileWriteCallback CB, void* Handle, const char* pFmt, ...)
  1878. {
  1879. char buffer[32*1024];
  1880. va_list args;
  1881. va_start (args, pFmt);
  1882. #ifdef _WIN32
  1883. size_t size = vsprintf_s(buffer, pFmt, args);
  1884. #else
  1885. size_t size = vsnprintf(buffer, sizeof(buffer)-1, pFmt, args);
  1886. #endif
  1887. CB(Handle, size, &buffer[0]);
  1888. va_end (args);
  1889. }
  1890. #define printf(...) MicroProfilePrintf(CB, Handle, __VA_ARGS__)
  1891. void MicroProfileDumpCsv(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames)
  1892. {
  1893. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  1894. float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  1895. float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu());
  1896. printf("frames,%d\n", nAggregateFrames);
  1897. printf("group,name,average,max,callaverage\n");
  1898. uint32_t nNumTimers = S.nTotalTimers;
  1899. uint32_t nBlockSize = 2 * nNumTimers;
  1900. float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float));
  1901. float* pAverage = pTimers + nBlockSize;
  1902. float* pMax = pTimers + 2 * nBlockSize;
  1903. float* pCallAverage = pTimers + 3 * nBlockSize;
  1904. float* pTimersExclusive = pTimers + 4 * nBlockSize;
  1905. float* pAverageExclusive = pTimers + 5 * nBlockSize;
  1906. float* pMaxExclusive = pTimers + 6 * nBlockSize;
  1907. float* pTotal = pTimers + 7 * nBlockSize;
  1908. MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers);
  1909. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  1910. {
  1911. uint32_t nIdx = i * 2;
  1912. printf("\"%s\",\"%s\",%f,%f,%f\n", S.TimerInfo[i].pName, S.GroupInfo[S.TimerInfo[i].nGroupIndex].pName, pAverage[nIdx], pMax[nIdx], pCallAverage[nIdx]);
  1913. }
  1914. printf("\n\n");
  1915. printf("group,average,max,total\n");
  1916. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1917. {
  1918. const char* pGroupName = S.GroupInfo[j].pName;
  1919. float fToMs = S.GroupInfo[j].Type == MicroProfileTokenTypeGpu ? fToMsGPU : fToMsCPU;
  1920. if(pGroupName[0] != '\0')
  1921. {
  1922. printf("\"%s\",%.3f,%.3f,%.3f\n", pGroupName, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j]);
  1923. }
  1924. }
  1925. printf("\n\n");
  1926. printf("group,thread,average,total\n");
  1927. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  1928. {
  1929. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  1930. {
  1931. if(S.Pool[i])
  1932. {
  1933. const char* pThreadName = &S.Pool[i]->ThreadName[0];
  1934. // MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i);
  1935. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  1936. {
  1937. uint64_t nTicks = S.Pool[i]->nAggregateGroupTicks[j];
  1938. float fTime = nTicks / nAggregateFrames * fToMs;
  1939. float fTimeTotal = nTicks * fToMs;
  1940. if(fTimeTotal > 0.01f)
  1941. {
  1942. const char* pGroupName = S.GroupInfo[j].pName;
  1943. printf("\"%s\",\"%s\",%.3f,%.3f\n", pGroupName, pThreadName, fTime, fTimeTotal);
  1944. }
  1945. }
  1946. }
  1947. }
  1948. }
  1949. printf("\n\n");
  1950. printf("frametimecpu\n");
  1951. const uint32_t nCount = MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3;
  1952. const uint32_t nStart = S.nFrameCurrent;
  1953. for(uint32_t i = nCount; i > 0; i--)
  1954. {
  1955. uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY;
  1956. uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1957. uint64_t nTicks = S.Frames[nFrameNext].nFrameStartCpu - S.Frames[nFrame].nFrameStartCpu;
  1958. printf("%f,", nTicks * fToMsCPU);
  1959. }
  1960. printf("\n");
  1961. printf("\n\n");
  1962. printf("frametimegpu\n");
  1963. for(uint32_t i = nCount; i > 0; i--)
  1964. {
  1965. uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY;
  1966. uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  1967. uint64_t nTicks = S.Frames[nFrameNext].nFrameStartGpu - S.Frames[nFrame].nFrameStartGpu;
  1968. printf("%f,", nTicks * fToMsGPU);
  1969. }
  1970. printf("\n\n");
  1971. printf("Meta\n");//only single frame snapshot
  1972. printf("name,average,max,total\n");
  1973. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  1974. {
  1975. if(S.MetaCounters[j].pName)
  1976. {
  1977. printf("\"%s\",%f,%lld,%lld\n",S.MetaCounters[j].pName, S.MetaCounters[j].nSumAggregate / (float)nAggregateFrames, S.MetaCounters[j].nSumAggregateMax,S.MetaCounters[j].nSumAggregate);
  1978. }
  1979. }
  1980. }
  1981. #undef printf
  1982. void MicroProfileDumpHtml(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames, const char* pHost)
  1983. {
  1984. uint32_t nRunning = S.nRunning;
  1985. S.nRunning = 0;
  1986. //stall pushing of timers
  1987. uint64_t nActiveGroup = S.nActiveGroup;
  1988. S.nActiveGroup = 0;
  1989. S.nPauseTicks = MP_TICK();
  1990. for(size_t i = 0; i < g_MicroProfileHtml_begin_count; ++i)
  1991. {
  1992. CB(Handle, g_MicroProfileHtml_begin_sizes[i]-1, g_MicroProfileHtml_begin[i]);
  1993. }
  1994. //dump info
  1995. uint64_t nTicks = MP_TICK();
  1996. float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  1997. float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu());
  1998. float fAggregateMs = fToMsCPU * (nTicks - S.nAggregateFlipTick);
  1999. MicroProfilePrintf(CB, Handle, "var DumpHost = '%s';\n", pHost ? pHost : "");
  2000. time_t CaptureTime;
  2001. time(&CaptureTime);
  2002. MicroProfilePrintf(CB, Handle, "var DumpUtcCaptureTime = %ld;\n", CaptureTime);
  2003. MicroProfilePrintf(CB, Handle, "var AggregateInfo = {'Frames':%d, 'Time':%f};\n", S.nAggregateFrames, fAggregateMs);
  2004. //categories
  2005. MicroProfilePrintf(CB, Handle, "var CategoryInfo = Array(%d);\n",S.nCategoryCount);
  2006. for(uint32_t i = 0; i < S.nCategoryCount; ++i)
  2007. {
  2008. MicroProfilePrintf(CB, Handle, "CategoryInfo[%d] = \"%s\";\n", i, S.CategoryInfo[i].pName);
  2009. }
  2010. //groups
  2011. MicroProfilePrintf(CB, Handle, "var GroupInfo = Array(%d);\n\n",S.nGroupCount);
  2012. uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1;
  2013. float fRcpAggregateFrames = 1.f / nAggregateFrames;
  2014. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2015. {
  2016. MP_ASSERT(i == S.GroupInfo[i].nGroupIndex);
  2017. float fToMs = S.GroupInfo[i].Type == MicroProfileTokenTypeCpu ? fToMsCPU : fToMsGPU;
  2018. MicroProfilePrintf(CB, Handle, "GroupInfo[%d] = MakeGroup(%d, \"%s\", %d, %d, %d, %f, %f, %f, '#%02x%02x%02x');\n",
  2019. S.GroupInfo[i].nGroupIndex,
  2020. S.GroupInfo[i].nGroupIndex,
  2021. S.GroupInfo[i].pName,
  2022. S.GroupInfo[i].nCategory,
  2023. S.GroupInfo[i].nNumTimers,
  2024. S.GroupInfo[i].Type == MicroProfileTokenTypeGpu?1:0,
  2025. fToMs * S.AggregateGroup[i],
  2026. fToMs * S.AggregateGroup[i] / nAggregateFrames,
  2027. fToMs * S.AggregateGroupMax[i],
  2028. MICROPROFILE_UNPACK_RED(S.GroupInfo[i].nColor) & 0xff,
  2029. MICROPROFILE_UNPACK_GREEN(S.GroupInfo[i].nColor) & 0xff,
  2030. MICROPROFILE_UNPACK_BLUE(S.GroupInfo[i].nColor) & 0xff);
  2031. }
  2032. //timers
  2033. uint32_t nNumTimers = S.nTotalTimers;
  2034. uint32_t nBlockSize = 2 * nNumTimers;
  2035. float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float));
  2036. float* pAverage = pTimers + nBlockSize;
  2037. float* pMax = pTimers + 2 * nBlockSize;
  2038. float* pCallAverage = pTimers + 3 * nBlockSize;
  2039. float* pTimersExclusive = pTimers + 4 * nBlockSize;
  2040. float* pAverageExclusive = pTimers + 5 * nBlockSize;
  2041. float* pMaxExclusive = pTimers + 6 * nBlockSize;
  2042. float* pTotal = pTimers + 7 * nBlockSize;
  2043. MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers);
  2044. MicroProfilePrintf(CB, Handle, "\nvar TimerInfo = Array(%d);\n\n", S.nTotalTimers);
  2045. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2046. {
  2047. uint32_t nIdx = i * 2;
  2048. MP_ASSERT(i == S.TimerInfo[i].nTimerIndex);
  2049. MicroProfilePrintf(CB, Handle, "var Meta%d = [", i);
  2050. bool bOnce = true;
  2051. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2052. {
  2053. if(S.MetaCounters[j].pName)
  2054. {
  2055. uint32_t lala = S.MetaCounters[j].nCounters[i];
  2056. MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", lala);
  2057. bOnce = false;
  2058. }
  2059. }
  2060. MicroProfilePrintf(CB, Handle, "];\n");
  2061. MicroProfilePrintf(CB, Handle, "var MetaAvg%d = [", i);
  2062. bOnce = true;
  2063. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2064. {
  2065. if(S.MetaCounters[j].pName)
  2066. {
  2067. MicroProfilePrintf(CB, Handle, bOnce ? "%f" : ",%f", fRcpAggregateFrames * S.MetaCounters[j].nAggregate[i]);
  2068. bOnce = false;
  2069. }
  2070. }
  2071. MicroProfilePrintf(CB, Handle, "];\n");
  2072. MicroProfilePrintf(CB, Handle, "var MetaMax%d = [", i);
  2073. bOnce = true;
  2074. for(int j = 0; j < MICROPROFILE_META_MAX; ++j)
  2075. {
  2076. if(S.MetaCounters[j].pName)
  2077. {
  2078. MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", S.MetaCounters[j].nAggregateMax[i]);
  2079. bOnce = false;
  2080. }
  2081. }
  2082. MicroProfilePrintf(CB, Handle, "];\n");
  2083. uint32_t nColor = S.TimerInfo[i].nColor;
  2084. uint32_t nColorDark = (nColor >> 1) & ~0x80808080;
  2085. 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,
  2086. MICROPROFILE_UNPACK_RED(nColor) & 0xff,
  2087. MICROPROFILE_UNPACK_GREEN(nColor) & 0xff,
  2088. MICROPROFILE_UNPACK_BLUE(nColor) & 0xff,
  2089. MICROPROFILE_UNPACK_RED(nColorDark) & 0xff,
  2090. MICROPROFILE_UNPACK_GREEN(nColorDark) & 0xff,
  2091. MICROPROFILE_UNPACK_BLUE(nColorDark) & 0xff,
  2092. pAverage[nIdx],
  2093. pMax[nIdx],
  2094. pAverageExclusive[nIdx],
  2095. pMaxExclusive[nIdx],
  2096. pCallAverage[nIdx],
  2097. S.Aggregate[i].nCount,
  2098. pTotal[nIdx],
  2099. i,i,i);
  2100. }
  2101. MicroProfilePrintf(CB, Handle, "\nvar ThreadNames = [");
  2102. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2103. {
  2104. if(S.Pool[i])
  2105. {
  2106. MicroProfilePrintf(CB, Handle, "'%s',", S.Pool[i]->ThreadName);
  2107. }
  2108. else
  2109. {
  2110. MicroProfilePrintf(CB, Handle, "'Thread %d',", i);
  2111. }
  2112. }
  2113. MicroProfilePrintf(CB, Handle, "];\n\n");
  2114. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2115. {
  2116. if(S.Pool[i])
  2117. {
  2118. MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i);
  2119. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  2120. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  2121. {
  2122. MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j]/nAggregateFrames * fToMs);
  2123. }
  2124. MicroProfilePrintf(CB, Handle, "];\n");
  2125. }
  2126. }
  2127. MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeArray = [");
  2128. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2129. {
  2130. if(S.Pool[i])
  2131. {
  2132. MicroProfilePrintf(CB, Handle, "ThreadGroupTime%d,", i);
  2133. }
  2134. }
  2135. MicroProfilePrintf(CB, Handle, "];\n");
  2136. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2137. {
  2138. if(S.Pool[i])
  2139. {
  2140. MicroProfilePrintf(CB, Handle, "var ThreadGroupTimeTotal%d = [", i);
  2141. float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU;
  2142. for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j)
  2143. {
  2144. MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j] * fToMs);
  2145. }
  2146. MicroProfilePrintf(CB, Handle, "];\n");
  2147. }
  2148. }
  2149. MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeTotalArray = [");
  2150. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2151. {
  2152. if(S.Pool[i])
  2153. {
  2154. MicroProfilePrintf(CB, Handle, "ThreadGroupTimeTotal%d,", i);
  2155. }
  2156. }
  2157. MicroProfilePrintf(CB, Handle, "];");
  2158. MicroProfilePrintf(CB, Handle, "\nvar ThreadIds = [");
  2159. for(uint32_t i = 0; i < S.nNumLogs; ++i)
  2160. {
  2161. if(S.Pool[i])
  2162. {
  2163. ThreadIdType ThreadId = S.Pool[i]->nThreadId;
  2164. if(!ThreadId)
  2165. {
  2166. ThreadId = (ThreadIdType)-1;
  2167. }
  2168. MicroProfilePrintf(CB, Handle, "%d,", ThreadId);
  2169. }
  2170. else
  2171. {
  2172. MicroProfilePrintf(CB, Handle, "-1,", i);
  2173. }
  2174. }
  2175. MicroProfilePrintf(CB, Handle, "];\n\n");
  2176. MicroProfilePrintf(CB, Handle, "\nvar MetaNames = [");
  2177. for(int i = 0; i < MICROPROFILE_META_MAX; ++i)
  2178. {
  2179. if(S.MetaCounters[i].pName)
  2180. {
  2181. MicroProfilePrintf(CB, Handle, "'%s',", S.MetaCounters[i].pName);
  2182. }
  2183. }
  2184. MicroProfilePrintf(CB, Handle, "];\n\n");
  2185. uint32_t nNumFrames = (MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3); //leave a few to not overwrite
  2186. nNumFrames = MicroProfileMin(nNumFrames, (uint32_t)nMaxFrames);
  2187. uint32_t nFirstFrame = (S.nFrameCurrent + MICROPROFILE_MAX_FRAME_HISTORY - nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY;
  2188. uint32_t nLastFrame = (nFirstFrame + nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY;
  2189. MP_ASSERT(nLastFrame == (S.nFrameCurrent % MICROPROFILE_MAX_FRAME_HISTORY));
  2190. MP_ASSERT(nFirstFrame < MICROPROFILE_MAX_FRAME_HISTORY);
  2191. MP_ASSERT(nLastFrame < MICROPROFILE_MAX_FRAME_HISTORY);
  2192. const int64_t nTickStart = S.Frames[nFirstFrame].nFrameStartCpu;
  2193. const int64_t nTickEnd = S.Frames[nLastFrame].nFrameStartCpu;
  2194. int64_t nTickStartGpu = S.Frames[nFirstFrame].nFrameStartGpu;
  2195. int64_t nTickReferenceCpu, nTickReferenceGpu;
  2196. int64_t nTicksPerSecondCpu = MicroProfileTicksPerSecondCpu();
  2197. int64_t nTicksPerSecondGpu = MicroProfileTicksPerSecondGpu();
  2198. int nTickReference = 0;
  2199. if(MicroProfileGetGpuTickReference(&nTickReferenceCpu, &nTickReferenceGpu))
  2200. {
  2201. nTickStartGpu = (nTickStart - nTickReferenceCpu) * nTicksPerSecondGpu / nTicksPerSecondCpu + nTickReferenceGpu;
  2202. nTickReference = 1;
  2203. }
  2204. #if MICROPROFILE_DEBUG
  2205. printf("dumping %d frames\n", nNumFrames);
  2206. printf("dumping frame %d to %d\n", nFirstFrame, nLastFrame);
  2207. #endif
  2208. uint32_t* nTimerCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers);
  2209. memset(nTimerCounter, 0, sizeof(uint32_t) * S.nTotalTimers);
  2210. MicroProfilePrintf(CB, Handle, "var Frames = Array(%d);\n", nNumFrames);
  2211. for(uint32_t i = 0; i < nNumFrames; ++i)
  2212. {
  2213. uint32_t nFrameIndex = (nFirstFrame + i) % MICROPROFILE_MAX_FRAME_HISTORY;
  2214. uint32_t nFrameIndexNext = (nFrameIndex + 1) % MICROPROFILE_MAX_FRAME_HISTORY;
  2215. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2216. {
  2217. MicroProfileThreadLog* pLog = S.Pool[j];
  2218. int64_t nStartTickBase = pLog->nGpu ? nTickStartGpu : nTickStart;
  2219. uint32_t nLogStart = S.Frames[nFrameIndex].nLogStart[j];
  2220. uint32_t nLogEnd = S.Frames[nFrameIndexNext].nLogStart[j];
  2221. float fToMsCpu = MicroProfileTickToMsMultiplier(nTicksPerSecondCpu);
  2222. float fToMsBase = MicroProfileTickToMsMultiplier(pLog->nGpu ? nTicksPerSecondGpu : nTicksPerSecondCpu);
  2223. MicroProfilePrintf(CB, Handle, "var ts_%d_%d = [", i, j);
  2224. if(nLogStart != nLogEnd)
  2225. {
  2226. uint32_t k = nLogStart;
  2227. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2228. float fToMs = nLogType == MP_LOG_GPU_EXTRA ? fToMsCpu : fToMsBase;
  2229. int64_t nStartTick = nLogType == MP_LOG_GPU_EXTRA ? nTickStart : nStartTickBase;
  2230. float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs;
  2231. MicroProfilePrintf(CB, Handle, "%f", fTime);
  2232. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2233. {
  2234. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2235. float fToMs = nLogType == MP_LOG_GPU_EXTRA ? fToMsCpu : fToMsBase;
  2236. nStartTick = nLogType == MP_LOG_GPU_EXTRA ? nTickStart : nStartTickBase;
  2237. float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs;
  2238. MicroProfilePrintf(CB, Handle, ",%f", fTime);
  2239. }
  2240. }
  2241. MicroProfilePrintf(CB, Handle, "];\n");
  2242. MicroProfilePrintf(CB, Handle, "var tt_%d_%d = [", i, j);
  2243. if(nLogStart != nLogEnd)
  2244. {
  2245. uint32_t k = nLogStart;
  2246. MicroProfilePrintf(CB, Handle, "%d", MicroProfileLogType(pLog->Log[k]));
  2247. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2248. {
  2249. uint32_t nLogType = MicroProfileLogType(pLog->Log[k]);
  2250. if(nLogType == MP_LOG_META)
  2251. {
  2252. //for meta, store the count + 3, which is the tick part
  2253. nLogType = 3 + MicroProfileLogGetTick(pLog->Log[k]);
  2254. }
  2255. MicroProfilePrintf(CB, Handle, ",%d", nLogType);
  2256. }
  2257. }
  2258. MicroProfilePrintf(CB, Handle, "];\n");
  2259. MicroProfilePrintf(CB, Handle, "var ti_%d_%d = [", i, j);
  2260. if(nLogStart != nLogEnd)
  2261. {
  2262. uint32_t k = nLogStart;
  2263. MicroProfilePrintf(CB, Handle, "%d", (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]));
  2264. for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE)
  2265. {
  2266. uint32_t nTimerIndex = (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]);
  2267. MicroProfilePrintf(CB, Handle, ",%d", nTimerIndex);
  2268. nTimerCounter[nTimerIndex]++;
  2269. }
  2270. }
  2271. MicroProfilePrintf(CB, Handle, "];\n");
  2272. }
  2273. MicroProfilePrintf(CB, Handle, "var ts%d = [", i);
  2274. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2275. {
  2276. MicroProfilePrintf(CB, Handle, "ts_%d_%d,", i, j);
  2277. }
  2278. MicroProfilePrintf(CB, Handle, "];\n");
  2279. MicroProfilePrintf(CB, Handle, "var tt%d = [", i);
  2280. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2281. {
  2282. MicroProfilePrintf(CB, Handle, "tt_%d_%d,", i, j);
  2283. }
  2284. MicroProfilePrintf(CB, Handle, "];\n");
  2285. MicroProfilePrintf(CB, Handle, "var ti%d = [", i);
  2286. for(uint32_t j = 0; j < S.nNumLogs; ++j)
  2287. {
  2288. MicroProfilePrintf(CB, Handle, "ti_%d_%d,", i, j);
  2289. }
  2290. MicroProfilePrintf(CB, Handle, "];\n");
  2291. int64_t nFrameStart = S.Frames[nFrameIndex].nFrameStartCpu;
  2292. int64_t nFrameEnd = S.Frames[nFrameIndexNext].nFrameStartCpu;
  2293. float fToMs = MicroProfileTickToMsMultiplier(nTicksPerSecondCpu);
  2294. float fFrameMs = MicroProfileLogTickDifference(nTickStart, nFrameStart) * fToMs;
  2295. float fFrameEndMs = MicroProfileLogTickDifference(nTickStart, nFrameEnd) * fToMs;
  2296. float fFrameGpuMs = 0;
  2297. float fFrameGpuEndMs = 0;
  2298. if(nTickReference)
  2299. {
  2300. fFrameGpuMs = MicroProfileLogTickDifference(nTickStartGpu, S.Frames[nFrameIndex].nFrameStartGpu) * fToMsGPU;
  2301. fFrameGpuEndMs = MicroProfileLogTickDifference(nTickStartGpu, S.Frames[nFrameIndexNext].nFrameStartGpu) * fToMsGPU;
  2302. }
  2303. 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);
  2304. }
  2305. uint32_t nContextSwitchStart = 0;
  2306. uint32_t nContextSwitchEnd = 0;
  2307. MicroProfileContextSwitchSearch(&nContextSwitchStart, &nContextSwitchEnd, nTickStart, nTickEnd);
  2308. uint32_t nWrittenBefore = S.nWebServerDataSent;
  2309. MicroProfilePrintf(CB, Handle, "var CSwitchThreadInOutCpu = [");
  2310. for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE)
  2311. {
  2312. MicroProfileContextSwitch CS = S.ContextSwitch[j];
  2313. int nCpu = CS.nCpu;
  2314. MicroProfilePrintf(CB, Handle, "%d,%d,%d,", CS.nThreadIn, CS.nThreadOut, nCpu);
  2315. }
  2316. MicroProfilePrintf(CB, Handle, "];\n");
  2317. MicroProfilePrintf(CB, Handle, "var CSwitchTime = [");
  2318. float fToMsCpu = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu());
  2319. for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE)
  2320. {
  2321. MicroProfileContextSwitch CS = S.ContextSwitch[j];
  2322. float fTime = MicroProfileLogTickDifference(nTickStart, CS.nTicks) * fToMsCpu;
  2323. MicroProfilePrintf(CB, Handle, "%f,", fTime);
  2324. }
  2325. MicroProfilePrintf(CB, Handle, "];\n");
  2326. uint32_t nWrittenAfter = S.nWebServerDataSent;
  2327. MicroProfilePrintf(CB, Handle, "//CSwitch Size %d\n", nWrittenAfter - nWrittenBefore);
  2328. for(size_t i = 0; i < g_MicroProfileHtml_end_count; ++i)
  2329. {
  2330. CB(Handle, g_MicroProfileHtml_end_sizes[i]-1, g_MicroProfileHtml_end[i]);
  2331. }
  2332. uint32_t* nGroupCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount);
  2333. memset(nGroupCounter, 0, sizeof(uint32_t) * S.nGroupCount);
  2334. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2335. {
  2336. uint32_t nGroupIndex = S.TimerInfo[i].nGroupIndex;
  2337. nGroupCounter[nGroupIndex] += nTimerCounter[i];
  2338. }
  2339. uint32_t* nGroupCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount);
  2340. uint32_t* nTimerCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers);
  2341. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2342. {
  2343. nGroupCounterSort[i] = i;
  2344. }
  2345. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2346. {
  2347. nTimerCounterSort[i] = i;
  2348. }
  2349. std::sort(nGroupCounterSort, nGroupCounterSort + S.nGroupCount,
  2350. [nGroupCounter](const uint32_t l, const uint32_t r)
  2351. {
  2352. return nGroupCounter[l] > nGroupCounter[r];
  2353. }
  2354. );
  2355. std::sort(nTimerCounterSort, nTimerCounterSort + S.nTotalTimers,
  2356. [nTimerCounter](const uint32_t l, const uint32_t r)
  2357. {
  2358. return nTimerCounter[l] > nTimerCounter[r];
  2359. }
  2360. );
  2361. MicroProfilePrintf(CB, Handle, "\n<!--\nMarker Per Group\n");
  2362. for(uint32_t i = 0; i < S.nGroupCount; ++i)
  2363. {
  2364. uint32_t idx = nGroupCounterSort[i];
  2365. MicroProfilePrintf(CB, Handle, "%8d:%s\n", nGroupCounter[idx], S.GroupInfo[idx].pName);
  2366. }
  2367. MicroProfilePrintf(CB, Handle, "Marker Per Timer\n");
  2368. for(uint32_t i = 0; i < S.nTotalTimers; ++i)
  2369. {
  2370. uint32_t idx = nTimerCounterSort[i];
  2371. MicroProfilePrintf(CB, Handle, "%8d:%s(%s)\n", nTimerCounter[idx], S.TimerInfo[idx].pName, S.GroupInfo[S.TimerInfo[idx].nGroupIndex].pName);
  2372. }
  2373. MicroProfilePrintf(CB, Handle, "\n-->\n");
  2374. S.nActiveGroup = nActiveGroup;
  2375. S.nRunning = nRunning;
  2376. #if MICROPROFILE_DEBUG
  2377. int64_t nTicksEnd = MP_TICK();
  2378. float fMs = fToMsCpu * (nTicksEnd - S.nPauseTicks);
  2379. printf("html dump took %6.2fms\n", fMs);
  2380. #endif
  2381. }
  2382. void MicroProfileWriteFile(void* Handle, size_t nSize, const char* pData)
  2383. {
  2384. fwrite(pData, nSize, 1, (FILE*)Handle);
  2385. }
  2386. void MicroProfileDumpToFile()
  2387. {
  2388. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  2389. if(S.nDumpFileNextFrame&1)
  2390. {
  2391. FILE* F = fopen(S.HtmlDumpPath, "w");
  2392. if(F)
  2393. {
  2394. MicroProfileDumpHtml(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES, S.HtmlDumpPath);
  2395. fclose(F);
  2396. }
  2397. }
  2398. if(S.nDumpFileNextFrame&2)
  2399. {
  2400. FILE* F = fopen(S.CsvDumpPath, "w");
  2401. if(F)
  2402. {
  2403. MicroProfileDumpCsv(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES);
  2404. fclose(F);
  2405. }
  2406. }
  2407. }
  2408. void MicroProfileFlushSocket(MpSocket Socket)
  2409. {
  2410. send(Socket, &S.WebServerBuffer[0], S.WebServerPut, 0);
  2411. S.WebServerPut = 0;
  2412. }
  2413. void MicroProfileWriteSocket(void* Handle, size_t nSize, const char* pData)
  2414. {
  2415. S.nWebServerDataSent += nSize;
  2416. MpSocket Socket = *(MpSocket*)Handle;
  2417. if(nSize > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE / 2)
  2418. {
  2419. MicroProfileFlushSocket(Socket);
  2420. send(Socket, pData, nSize, 0);
  2421. }
  2422. else
  2423. {
  2424. memcpy(&S.WebServerBuffer[S.WebServerPut], pData, nSize);
  2425. S.WebServerPut += nSize;
  2426. if(S.WebServerPut > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE/2)
  2427. {
  2428. MicroProfileFlushSocket(Socket);
  2429. }
  2430. }
  2431. }
  2432. #if MICROPROFILE_MINIZ
  2433. #ifndef MICROPROFILE_COMPRESS_BUFFER_SIZE
  2434. #define MICROPROFILE_COMPRESS_BUFFER_SIZE (256<<10)
  2435. #endif
  2436. #define MICROPROFILE_COMPRESS_CHUNK (MICROPROFILE_COMPRESS_BUFFER_SIZE/2)
  2437. struct MicroProfileCompressedSocketState
  2438. {
  2439. unsigned char DeflateOut[MICROPROFILE_COMPRESS_CHUNK];
  2440. unsigned char DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2441. mz_stream Stream;
  2442. MpSocket Socket;
  2443. uint32_t nSize;
  2444. uint32_t nCompressedSize;
  2445. uint32_t nFlushes;
  2446. uint32_t nMemmoveBytes;
  2447. };
  2448. void MicroProfileCompressedSocketFlush(MicroProfileCompressedSocketState* pState)
  2449. {
  2450. mz_stream& Stream = pState->Stream;
  2451. unsigned char* pSendStart = &pState->DeflateOut[0];
  2452. unsigned char* pSendEnd = &pState->DeflateOut[MICROPROFILE_COMPRESS_CHUNK - Stream.avail_out];
  2453. if(pSendStart != pSendEnd)
  2454. {
  2455. send(pState->Socket, (const char*)pSendStart, pSendEnd - pSendStart, 0);
  2456. pState->nCompressedSize += pSendEnd - pSendStart;
  2457. }
  2458. Stream.next_out = &pState->DeflateOut[0];
  2459. Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK;
  2460. }
  2461. void MicroProfileCompressedSocketStart(MicroProfileCompressedSocketState* pState, MpSocket Socket)
  2462. {
  2463. mz_stream& Stream = pState->Stream;
  2464. memset(&Stream, 0, sizeof(Stream));
  2465. Stream.next_out = &pState->DeflateOut[0];
  2466. Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK;
  2467. Stream.next_in = &pState->DeflateIn[0];
  2468. Stream.avail_in = 0;
  2469. mz_deflateInit(&Stream, Z_DEFAULT_COMPRESSION);
  2470. pState->Socket = Socket;
  2471. pState->nSize = 0;
  2472. pState->nCompressedSize = 0;
  2473. pState->nFlushes = 0;
  2474. pState->nMemmoveBytes = 0;
  2475. }
  2476. void MicroProfileCompressedSocketFinish(MicroProfileCompressedSocketState* pState)
  2477. {
  2478. mz_stream& Stream = pState->Stream;
  2479. MicroProfileCompressedSocketFlush(pState);
  2480. int r = mz_deflate(&Stream, MZ_FINISH);
  2481. MP_ASSERT(r == MZ_STREAM_END);
  2482. MicroProfileCompressedSocketFlush(pState);
  2483. r = mz_deflateEnd(&Stream);
  2484. MP_ASSERT(r == MZ_OK);
  2485. }
  2486. void MicroProfileCompressedWriteSocket(void* Handle, size_t nSize, const char* pData)
  2487. {
  2488. MicroProfileCompressedSocketState* pState = (MicroProfileCompressedSocketState*)Handle;
  2489. mz_stream& Stream = pState->Stream;
  2490. const unsigned char* pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2491. const unsigned char* pDeflateInStart = &pState->DeflateIn[0];
  2492. const unsigned char* pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2493. pState->nSize += nSize;
  2494. if(nSize <= pDeflateInRealEnd - pDeflateInEnd)
  2495. {
  2496. memcpy((void*)pDeflateInEnd, pData, nSize);
  2497. Stream.avail_in += nSize;
  2498. MP_ASSERT(Stream.next_in + Stream.avail_in <= pDeflateInRealEnd);
  2499. return;
  2500. }
  2501. int Flush = 0;
  2502. while(nSize)
  2503. {
  2504. pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2505. if(Flush)
  2506. {
  2507. pState->nFlushes++;
  2508. MicroProfileCompressedSocketFlush(pState);
  2509. pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK];
  2510. if(pDeflateInEnd == pDeflateInRealEnd)
  2511. {
  2512. if(Stream.avail_in)
  2513. {
  2514. MP_ASSERT(pDeflateInStart != Stream.next_in);
  2515. memmove((void*)pDeflateInStart, Stream.next_in, Stream.avail_in);
  2516. pState->nMemmoveBytes += Stream.avail_in;
  2517. }
  2518. Stream.next_in = pDeflateInStart;
  2519. pDeflateInEnd = Stream.next_in + Stream.avail_in;
  2520. }
  2521. }
  2522. size_t nSpace = pDeflateInRealEnd - pDeflateInEnd;
  2523. size_t nBytes = MicroProfileMin(nSpace, nSize);
  2524. MP_ASSERT(nBytes + pDeflateInEnd <= pDeflateInRealEnd);
  2525. memcpy((void*)pDeflateInEnd, pData, nBytes);
  2526. Stream.avail_in += nBytes;
  2527. nSize -= nBytes;
  2528. pData += nBytes;
  2529. int r = mz_deflate(&Stream, MZ_NO_FLUSH);
  2530. Flush = r == MZ_BUF_ERROR || nBytes == 0 || Stream.avail_out == 0 ? 1 : 0;
  2531. MP_ASSERT(r == MZ_BUF_ERROR || r == MZ_OK);
  2532. if(r == MZ_BUF_ERROR)
  2533. {
  2534. r = mz_deflate(&Stream, MZ_SYNC_FLUSH);
  2535. }
  2536. }
  2537. }
  2538. #endif
  2539. #ifndef MicroProfileSetNonBlocking //fcntl doesnt work on a some unix like platforms..
  2540. void MicroProfileSetNonBlocking(MpSocket Socket, int NonBlocking)
  2541. {
  2542. #ifdef _WIN32
  2543. u_long nonBlocking = NonBlocking ? 1 : 0;
  2544. ioctlsocket(Socket, FIONBIO, &nonBlocking);
  2545. #else
  2546. int Options = fcntl(Socket, F_GETFL);
  2547. if(NonBlocking)
  2548. {
  2549. fcntl(Socket, F_SETFL, Options|O_NONBLOCK);
  2550. }
  2551. else
  2552. {
  2553. fcntl(Socket, F_SETFL, Options&(~O_NONBLOCK));
  2554. }
  2555. #endif
  2556. }
  2557. #endif
  2558. void MicroProfileWebServerStart()
  2559. {
  2560. #ifdef _WIN32
  2561. WSADATA wsa;
  2562. if(WSAStartup(MAKEWORD(2, 2), &wsa))
  2563. {
  2564. S.ListenerSocket = -1;
  2565. return;
  2566. }
  2567. #endif
  2568. S.ListenerSocket = socket(PF_INET, SOCK_STREAM, 6);
  2569. MP_ASSERT(!MP_INVALID_SOCKET(S.ListenerSocket));
  2570. MicroProfileSetNonBlocking(S.ListenerSocket, 1);
  2571. S.nWebServerPort = (uint32_t)-1;
  2572. struct sockaddr_in Addr;
  2573. Addr.sin_family = AF_INET;
  2574. Addr.sin_addr.s_addr = INADDR_ANY;
  2575. for(int i = 0; i < 20; ++i)
  2576. {
  2577. Addr.sin_port = htons(MICROPROFILE_WEBSERVER_PORT+i);
  2578. if(0 == bind(S.ListenerSocket, (sockaddr*)&Addr, sizeof(Addr)))
  2579. {
  2580. S.nWebServerPort = MICROPROFILE_WEBSERVER_PORT+i;
  2581. break;
  2582. }
  2583. }
  2584. listen(S.ListenerSocket, 8);
  2585. }
  2586. void MicroProfileWebServerStop()
  2587. {
  2588. #ifdef _WIN32
  2589. closesocket(S.ListenerSocket);
  2590. WSACleanup();
  2591. #else
  2592. close(S.ListenerSocket);
  2593. #endif
  2594. }
  2595. int MicroProfileParseGet(const char* pGet)
  2596. {
  2597. const char* pStart = pGet;
  2598. while(*pGet != '\0')
  2599. {
  2600. if(*pGet < '0' || *pGet > '9')
  2601. return 0;
  2602. pGet++;
  2603. }
  2604. int nFrames = atoi(pStart);
  2605. if(nFrames)
  2606. {
  2607. return nFrames;
  2608. }
  2609. else
  2610. {
  2611. return MICROPROFILE_WEBSERVER_MAXFRAMES;
  2612. }
  2613. }
  2614. bool MicroProfileWebServerUpdate()
  2615. {
  2616. MICROPROFILE_SCOPEI("MicroProfile", "Webserver-update", -1);
  2617. MpSocket Connection = accept(S.ListenerSocket, 0, 0);
  2618. bool bServed = false;
  2619. if(!MP_INVALID_SOCKET(Connection))
  2620. {
  2621. std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex());
  2622. char Req[8192];
  2623. MicroProfileSetNonBlocking(Connection, 0);
  2624. int nReceived = recv(Connection, Req, sizeof(Req)-1, 0);
  2625. if(nReceived > 0)
  2626. {
  2627. Req[nReceived] = '\0';
  2628. #if MICROPROFILE_MINIZ
  2629. #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"
  2630. #else
  2631. #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"
  2632. #endif
  2633. char* pHttp = strstr(Req, "HTTP/");
  2634. char* pGet = strstr(Req, "GET /");
  2635. char* pHost = strstr(Req, "Host: ");
  2636. auto Terminate = [](char* pString)
  2637. {
  2638. char* pEnd = pString;
  2639. while(*pEnd != '\0')
  2640. {
  2641. if(*pEnd == '\r' || *pEnd == '\n' || *pEnd == ' ')
  2642. {
  2643. *pEnd = '\0';
  2644. return;
  2645. }
  2646. pEnd++;
  2647. }
  2648. };
  2649. if(pHost)
  2650. {
  2651. pHost += sizeof("Host: ")-1;
  2652. Terminate(pHost);
  2653. }
  2654. if(pHttp && pGet)
  2655. {
  2656. *pHttp = '\0';
  2657. pGet += sizeof("GET /")-1;
  2658. Terminate(pGet);
  2659. int nFrames = MicroProfileParseGet(pGet);
  2660. if(nFrames)
  2661. {
  2662. uint64_t nTickStart = MP_TICK();
  2663. send(Connection, MICROPROFILE_HTML_HEADER, sizeof(MICROPROFILE_HTML_HEADER)-1, 0);
  2664. uint64_t nDataStart = S.nWebServerDataSent;
  2665. S.WebServerPut = 0;
  2666. #if 0 == MICROPROFILE_MINIZ
  2667. MicroProfileDumpHtml(MicroProfileWriteSocket, &Connection, nFrames, pHost);
  2668. uint64_t nDataEnd = S.nWebServerDataSent;
  2669. uint64_t nTickEnd = MP_TICK();
  2670. uint64_t nDiff = (nTickEnd - nTickStart);
  2671. float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff;
  2672. int nKb = ((nDataEnd-nDataStart)>>10) + 1;
  2673. int nCompressedKb = nKb;
  2674. MicroProfilePrintf(MicroProfileWriteSocket, &Connection, "\n<!-- Sent %dkb in %.2fms-->\n\n",nKb, fMs);
  2675. MicroProfileFlushSocket(Connection);
  2676. #else
  2677. MicroProfileCompressedSocketState CompressState;
  2678. MicroProfileCompressedSocketStart(&CompressState, Connection);
  2679. MicroProfileDumpHtml(MicroProfileCompressedWriteSocket, &CompressState, nFrames, pHost);
  2680. S.nWebServerDataSent += CompressState.nSize;
  2681. uint64_t nDataEnd = S.nWebServerDataSent;
  2682. uint64_t nTickEnd = MP_TICK();
  2683. uint64_t nDiff = (nTickEnd - nTickStart);
  2684. float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff;
  2685. int nKb = ((nDataEnd-nDataStart)>>10) + 1;
  2686. int nCompressedKb = ((CompressState.nCompressedSize)>>10) + 1;
  2687. MicroProfilePrintf(MicroProfileCompressedWriteSocket, &CompressState, "\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs);
  2688. MicroProfileCompressedSocketFinish(&CompressState);
  2689. MicroProfileFlushSocket(Connection);
  2690. #endif
  2691. #if MICROPROFILE_DEBUG
  2692. printf("\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs);
  2693. #endif
  2694. }
  2695. }
  2696. }
  2697. #ifdef _WIN32
  2698. closesocket(Connection);
  2699. #else
  2700. close(Connection);
  2701. #endif
  2702. }
  2703. return bServed;
  2704. }
  2705. #endif
  2706. #if MICROPROFILE_CONTEXT_SWITCH_TRACE
  2707. //functions that need to be implemented per platform.
  2708. void* MicroProfileTraceThread(void* unused);
  2709. bool MicroProfileIsLocalThread(uint32_t nThreadId);
  2710. void MicroProfileStartContextSwitchTrace()
  2711. {
  2712. if(!S.bContextSwitchRunning)
  2713. {
  2714. S.bContextSwitchRunning = true;
  2715. S.bContextSwitchStop = false;
  2716. MicroProfileThreadStart(&S.ContextSwitchThread, MicroProfileTraceThread);
  2717. }
  2718. }
  2719. void MicroProfileStopContextSwitchTrace()
  2720. {
  2721. if(S.bContextSwitchRunning)
  2722. {
  2723. S.bContextSwitchStop = true;
  2724. MicroProfileThreadJoin(&S.ContextSwitchThread);
  2725. }
  2726. }
  2727. #ifdef _WIN32
  2728. #define INITGUID
  2729. #include <evntrace.h>
  2730. #include <evntcons.h>
  2731. #include <strsafe.h>
  2732. static GUID g_MicroProfileThreadClassGuid = { 0x3d6fa8d1, 0xfe05, 0x11d0, 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c };
  2733. struct MicroProfileSCSwitch
  2734. {
  2735. uint32_t NewThreadId;
  2736. uint32_t OldThreadId;
  2737. int8_t NewThreadPriority;
  2738. int8_t OldThreadPriority;
  2739. uint8_t PreviousCState;
  2740. int8_t SpareByte;
  2741. int8_t OldThreadWaitReason;
  2742. int8_t OldThreadWaitMode;
  2743. int8_t OldThreadState;
  2744. int8_t OldThreadWaitIdealProcessor;
  2745. uint32_t NewThreadWaitTime;
  2746. uint32_t Reserved;
  2747. };
  2748. VOID WINAPI MicroProfileContextSwitchCallback(PEVENT_TRACE pEvent)
  2749. {
  2750. if (pEvent->Header.Guid == g_MicroProfileThreadClassGuid)
  2751. {
  2752. if (pEvent->Header.Class.Type == 36)
  2753. {
  2754. MicroProfileSCSwitch* pCSwitch = (MicroProfileSCSwitch*) pEvent->MofData;
  2755. if ((pCSwitch->NewThreadId != 0) || (pCSwitch->OldThreadId != 0))
  2756. {
  2757. MicroProfileContextSwitch Switch;
  2758. Switch.nThreadOut = pCSwitch->OldThreadId;
  2759. Switch.nThreadIn = pCSwitch->NewThreadId;
  2760. Switch.nCpu = pEvent->BufferContext.ProcessorNumber;
  2761. Switch.nTicks = pEvent->Header.TimeStamp.QuadPart;
  2762. MicroProfileContextSwitchPut(&Switch);
  2763. }
  2764. }
  2765. }
  2766. }
  2767. ULONG WINAPI MicroProfileBufferCallback(PEVENT_TRACE_LOGFILE Buffer)
  2768. {
  2769. return (S.bContextSwitchStop || !S.bContextSwitchRunning) ? FALSE : TRUE;
  2770. }
  2771. struct MicroProfileKernelTraceProperties : public EVENT_TRACE_PROPERTIES
  2772. {
  2773. char dummy[sizeof(KERNEL_LOGGER_NAME)];
  2774. };
  2775. void MicroProfileContextSwitchShutdownTrace()
  2776. {
  2777. TRACEHANDLE SessionHandle = 0;
  2778. MicroProfileKernelTraceProperties sessionProperties;
  2779. ZeroMemory(&sessionProperties, sizeof(sessionProperties));
  2780. sessionProperties.Wnode.BufferSize = sizeof(sessionProperties);
  2781. sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
  2782. sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution
  2783. sessionProperties.Wnode.Guid = SystemTraceControlGuid;
  2784. sessionProperties.BufferSize = 1;
  2785. sessionProperties.NumberOfBuffers = 128;
  2786. sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH;
  2787. sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  2788. sessionProperties.MaximumFileSize = 0;
  2789. sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
  2790. sessionProperties.LogFileNameOffset = 0;
  2791. EVENT_TRACE_LOGFILE log;
  2792. ZeroMemory(&log, sizeof(log));
  2793. log.LoggerName = KERNEL_LOGGER_NAME;
  2794. log.ProcessTraceMode = 0;
  2795. TRACEHANDLE hLog = OpenTrace(&log);
  2796. if (hLog)
  2797. {
  2798. ControlTrace(SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties, EVENT_TRACE_CONTROL_STOP);
  2799. }
  2800. CloseTrace(hLog);
  2801. }
  2802. void* MicroProfileTraceThread(void* unused)
  2803. {
  2804. MicroProfileContextSwitchShutdownTrace();
  2805. ULONG status = ERROR_SUCCESS;
  2806. TRACEHANDLE SessionHandle = 0;
  2807. MicroProfileKernelTraceProperties sessionProperties;
  2808. ZeroMemory(&sessionProperties, sizeof(sessionProperties));
  2809. sessionProperties.Wnode.BufferSize = sizeof(sessionProperties);
  2810. sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
  2811. sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution
  2812. sessionProperties.Wnode.Guid = SystemTraceControlGuid;
  2813. sessionProperties.BufferSize = 1;
  2814. sessionProperties.NumberOfBuffers = 128;
  2815. sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH|EVENT_TRACE_FLAG_PROCESS;
  2816. sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
  2817. sessionProperties.MaximumFileSize = 0;
  2818. sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
  2819. sessionProperties.LogFileNameOffset = 0;
  2820. status = StartTrace((PTRACEHANDLE) &SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties);
  2821. if (ERROR_SUCCESS != status)
  2822. {
  2823. S.bContextSwitchRunning = false;
  2824. return 0;
  2825. }
  2826. EVENT_TRACE_LOGFILE log;
  2827. ZeroMemory(&log, sizeof(log));
  2828. log.LoggerName = KERNEL_LOGGER_NAME;
  2829. log.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_RAW_TIMESTAMP;
  2830. log.EventCallback = MicroProfileContextSwitchCallback;
  2831. log.BufferCallback = MicroProfileBufferCallback;
  2832. TRACEHANDLE hLog = OpenTrace(&log);
  2833. ProcessTrace(&hLog, 1, 0, 0);
  2834. CloseTrace(hLog);
  2835. MicroProfileContextSwitchShutdownTrace();
  2836. S.bContextSwitchRunning = false;
  2837. return 0;
  2838. }
  2839. bool MicroProfileIsLocalThread(uint32_t nThreadId)
  2840. {
  2841. HANDLE h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, nThreadId);
  2842. if(h == NULL)
  2843. return false;
  2844. DWORD hProcess = GetProcessIdOfThread(h);
  2845. CloseHandle(h);
  2846. return GetCurrentProcessId() == hProcess;
  2847. }
  2848. #elif defined(__APPLE__)
  2849. #include <sys/time.h>
  2850. void* MicroProfileTraceThread(void* unused)
  2851. {
  2852. FILE* pFile = fopen("mypipe", "r");
  2853. if(!pFile)
  2854. {
  2855. printf("CONTEXT SWITCH FAILED TO OPEN FILE: make sure to run dtrace script\n");
  2856. S.bContextSwitchRunning = false;
  2857. return 0;
  2858. }
  2859. printf("STARTING TRACE THREAD\n");
  2860. char* pLine = 0;
  2861. size_t cap = 0;
  2862. size_t len = 0;
  2863. struct timeval tv;
  2864. gettimeofday(&tv, NULL);
  2865. uint64_t nsSinceEpoch = ((uint64_t)(tv.tv_sec) * 1000000 + (uint64_t)(tv.tv_usec)) * 1000;
  2866. uint64_t nTickEpoch = MP_TICK();
  2867. uint32_t nLastThread[MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS] = {0};
  2868. mach_timebase_info_data_t sTimebaseInfo;
  2869. mach_timebase_info(&sTimebaseInfo);
  2870. S.bContextSwitchRunning = true;
  2871. uint64_t nProcessed = 0;
  2872. uint64_t nProcessedLast = 0;
  2873. while((len = getline(&pLine, &cap, pFile))>0 && !S.bContextSwitchStop)
  2874. {
  2875. nProcessed += len;
  2876. if(nProcessed - nProcessedLast > 10<<10)
  2877. {
  2878. nProcessedLast = nProcessed;
  2879. printf("processed %llukb %llukb\n", (nProcessed-nProcessedLast)>>10,nProcessed >>10);
  2880. }
  2881. char* pX = strchr(pLine, 'X');
  2882. if(pX)
  2883. {
  2884. int cpu = atoi(pX+1);
  2885. char* pX2 = strchr(pX + 1, 'X');
  2886. char* pX3 = strchr(pX2 + 1, 'X');
  2887. int thread = atoi(pX2+1);
  2888. char* lala;
  2889. int64_t timestamp = strtoll(pX3 + 1, &lala, 10);
  2890. MicroProfileContextSwitch Switch;
  2891. //convert to ticks.
  2892. uint64_t nDeltaNsSinceEpoch = timestamp - nsSinceEpoch;
  2893. uint64_t nDeltaTickSinceEpoch = sTimebaseInfo.numer * nDeltaNsSinceEpoch / sTimebaseInfo.denom;
  2894. uint64_t nTicks = nDeltaTickSinceEpoch + nTickEpoch;
  2895. if(cpu < MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS)
  2896. {
  2897. Switch.nThreadOut = nLastThread[cpu];
  2898. Switch.nThreadIn = thread;
  2899. nLastThread[cpu] = thread;
  2900. Switch.nCpu = cpu;
  2901. Switch.nTicks = nTicks;
  2902. MicroProfileContextSwitchPut(&Switch);
  2903. }
  2904. }
  2905. }
  2906. printf("EXITING TRACE THREAD\n");
  2907. S.bContextSwitchRunning = false;
  2908. return 0;
  2909. }
  2910. bool MicroProfileIsLocalThread(uint32_t nThreadId)
  2911. {
  2912. return false;
  2913. }
  2914. #endif
  2915. #else
  2916. bool MicroProfileIsLocalThread([[maybe_unused]] uint32_t nThreadId) { return false; }
  2917. void MicroProfileStopContextSwitchTrace(){}
  2918. void MicroProfileStartContextSwitchTrace(){}
  2919. #endif
  2920. #if MICROPROFILE_GPU_TIMERS_D3D11
  2921. uint32_t MicroProfileGpuInsertTimeStamp()
  2922. {
  2923. MicroProfileD3D11Frame& Frame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame];
  2924. if(Frame.m_nRateQueryStarted)
  2925. {
  2926. uint32_t nCurrent = (Frame.m_nQueryStart + Frame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES;
  2927. uint32_t nNext = (nCurrent + 1) % MICROPROFILE_D3D_MAX_QUERIES;
  2928. if(nNext != S.GPU.m_nQueryGet)
  2929. {
  2930. Frame.m_nQueryCount++;
  2931. ID3D11Query* pQuery = (ID3D11Query*)S.GPU.m_pQueries[nCurrent];
  2932. ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext;
  2933. pContext->End(pQuery);
  2934. S.GPU.m_nQueryPut = nNext;
  2935. return nCurrent;
  2936. }
  2937. }
  2938. return (uint32_t)-1;
  2939. }
  2940. uint64_t MicroProfileGpuGetTimeStamp(uint32_t nIndex)
  2941. {
  2942. if(nIndex == (uint32_t)-1)
  2943. {
  2944. return (uint64_t)-1;
  2945. }
  2946. int64_t nResult = S.GPU.m_nQueryResults[nIndex];
  2947. MP_ASSERT(nResult != -1);
  2948. return nResult;
  2949. }
  2950. bool MicroProfileGpuGetData(void* pQuery, void* pData, uint32_t nDataSize)
  2951. {
  2952. HRESULT hr;
  2953. do
  2954. {
  2955. hr = ((ID3D11DeviceContext*)S.GPU.m_pDeviceContext)->GetData((ID3D11Query*)pQuery, pData, nDataSize, 0);
  2956. }while(hr == S_FALSE);
  2957. switch(hr)
  2958. {
  2959. case DXGI_ERROR_DEVICE_REMOVED:
  2960. case DXGI_ERROR_INVALID_CALL:
  2961. case E_INVALIDARG:
  2962. MP_BREAK();
  2963. return false;
  2964. }
  2965. return true;
  2966. }
  2967. uint64_t MicroProfileTicksPerSecondGpu()
  2968. {
  2969. return S.GPU.m_nQueryFrequency;
  2970. }
  2971. void MicroProfileGpuFlip()
  2972. {
  2973. MicroProfileD3D11Frame& CurrentFrame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame];
  2974. ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext;
  2975. if(CurrentFrame.m_nRateQueryStarted)
  2976. {
  2977. pContext->End((ID3D11Query*)CurrentFrame.m_pRateQuery);
  2978. }
  2979. uint32_t nNextFrame = (S.GPU.m_nQueryFrame + 1) % MICROPROFILE_GPU_FRAME_DELAY;
  2980. MicroProfileD3D11Frame& OldFrame = S.GPU.m_QueryFrames[nNextFrame];
  2981. if(OldFrame.m_nRateQueryStarted)
  2982. {
  2983. struct RateQueryResult
  2984. {
  2985. uint64_t nFrequency;
  2986. BOOL bDisjoint;
  2987. };
  2988. RateQueryResult Result;
  2989. if(MicroProfileGpuGetData(OldFrame.m_pRateQuery, &Result, sizeof(Result)))
  2990. {
  2991. if(S.GPU.m_nQueryFrequency != (int64_t)Result.nFrequency)
  2992. {
  2993. if(S.GPU.m_nQueryFrequency)
  2994. {
  2995. OutputDebugString("Query freq changing");
  2996. }
  2997. S.GPU.m_nQueryFrequency = Result.nFrequency;
  2998. }
  2999. uint32_t nStart = OldFrame.m_nQueryStart;
  3000. uint32_t nCount = OldFrame.m_nQueryCount;
  3001. for(uint32_t i = 0; i < nCount; ++i)
  3002. {
  3003. uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES;
  3004. if(!MicroProfileGpuGetData(S.GPU.m_pQueries[nIndex], &S.GPU.m_nQueryResults[nIndex], sizeof(uint64_t)))
  3005. {
  3006. S.GPU.m_nQueryResults[nIndex] = -1;
  3007. }
  3008. }
  3009. }
  3010. else
  3011. {
  3012. uint32_t nStart = OldFrame.m_nQueryStart;
  3013. uint32_t nCount = OldFrame.m_nQueryCount;
  3014. for(uint32_t i = 0; i < nCount; ++i)
  3015. {
  3016. uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES;
  3017. S.GPU.m_nQueryResults[nIndex] = -1;
  3018. }
  3019. }
  3020. S.GPU.m_nQueryGet = (OldFrame.m_nQueryStart + OldFrame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES;
  3021. }
  3022. S.GPU.m_nQueryFrame = nNextFrame;
  3023. MicroProfileD3D11Frame& NextFrame = S.GPU.m_QueryFrames[nNextFrame];
  3024. pContext->Begin((ID3D11Query*)NextFrame.m_pRateQuery);
  3025. NextFrame.m_nQueryStart = S.GPU.m_nQueryPut;
  3026. NextFrame.m_nQueryCount = 0;
  3027. NextFrame.m_nRateQueryStarted = 1;
  3028. }
  3029. void MicroProfileGpuInitD3D11(void* pDevice_, void* pDeviceContext_)
  3030. {
  3031. ID3D11Device* pDevice = (ID3D11Device*)pDevice_;
  3032. ID3D11DeviceContext* pDeviceContext = (ID3D11DeviceContext*)pDeviceContext_;
  3033. S.GPU.m_pDeviceContext = pDeviceContext_;
  3034. D3D11_QUERY_DESC Desc;
  3035. Desc.MiscFlags = 0;
  3036. Desc.Query = D3D11_QUERY_TIMESTAMP;
  3037. for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i)
  3038. {
  3039. HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_pQueries[i]);
  3040. MP_ASSERT(hr == S_OK);
  3041. S.GPU.m_nQueryResults[i] = -1;
  3042. }
  3043. S.GPU.m_nQueryPut = 0;
  3044. S.GPU.m_nQueryGet = 0;
  3045. S.GPU.m_nQueryFrame = 0;
  3046. S.GPU.m_nQueryFrequency = 0;
  3047. Desc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
  3048. for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i)
  3049. {
  3050. S.GPU.m_QueryFrames[i].m_nQueryStart = 0;
  3051. S.GPU.m_QueryFrames[i].m_nQueryCount = 0;
  3052. S.GPU.m_QueryFrames[i].m_nRateQueryStarted = 0;
  3053. HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_QueryFrames[i].m_pRateQuery);
  3054. MP_ASSERT(hr == S_OK);
  3055. }
  3056. }
  3057. void MicroProfileGpuShutdown()
  3058. {
  3059. for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i)
  3060. {
  3061. ((ID3D11Query*)&S.GPU.m_pQueries[i])->Release();
  3062. S.GPU.m_pQueries[i] = 0;
  3063. }
  3064. for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i)
  3065. {
  3066. ((ID3D11Query*)S.GPU.m_QueryFrames[i].m_pRateQuery)->Release();
  3067. S.GPU.m_QueryFrames[i].m_pRateQuery = 0;
  3068. }
  3069. }
  3070. int MicroProfileGetGpuTickReference(int64_t* pOutCPU, int64_t* pOutGpu)
  3071. {
  3072. return 0;
  3073. }
  3074. #elif MICROPROFILE_GPU_TIMERS_GL
  3075. void MicroProfileGpuInitGL()
  3076. {
  3077. S.GPU.GLTimerPos = 0;
  3078. glGenQueries(MICROPROFILE_GL_MAX_QUERIES, &S.GPU.GLTimers[0]);
  3079. }
  3080. uint32_t MicroProfileGpuInsertTimeStamp()
  3081. {
  3082. uint32_t nIndex = (S.GPU.GLTimerPos+1)%MICROPROFILE_GL_MAX_QUERIES;
  3083. glQueryCounter(S.GPU.GLTimers[nIndex], GL_TIMESTAMP);
  3084. S.GPU.GLTimerPos = nIndex;
  3085. return nIndex;
  3086. }
  3087. uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey)
  3088. {
  3089. uint64_t result;
  3090. glGetQueryObjectui64v(S.GPU.GLTimers[nKey], GL_QUERY_RESULT, &result);
  3091. return result;
  3092. }
  3093. uint64_t MicroProfileTicksPerSecondGpu()
  3094. {
  3095. return 1000000000ll;
  3096. }
  3097. int MicroProfileGetGpuTickReference(int64_t* pOutCpu, int64_t* pOutGpu)
  3098. {
  3099. int64_t nGpuTimeStamp;
  3100. glGetInteger64v(GL_TIMESTAMP, &nGpuTimeStamp);
  3101. if(nGpuTimeStamp)
  3102. {
  3103. *pOutCpu = MP_TICK();
  3104. *pOutGpu = nGpuTimeStamp;
  3105. #if 0 //debug test if timestamp diverges
  3106. static int64_t nTicksPerSecondCpu = MicroProfileTicksPerSecondCpu();
  3107. static int64_t nTicksPerSecondGpu = MicroProfileTicksPerSecondGpu();
  3108. static int64_t nGpuStart = 0;
  3109. static int64_t nCpuStart = 0;
  3110. if(!nCpuStart)
  3111. {
  3112. nCpuStart = *pOutCpu;
  3113. nGpuStart = *pOutGpu;
  3114. }
  3115. static int nCountDown = 100;
  3116. if(0 == nCountDown--)
  3117. {
  3118. int64_t nCurCpu = *pOutCpu;
  3119. int64_t nCurGpu = *pOutGpu;
  3120. double fDistanceCpu = (nCurCpu - nCpuStart) / (double)nTicksPerSecondCpu;
  3121. double fDistanceGpu = (nCurGpu - nGpuStart) / (double)nTicksPerSecondGpu;
  3122. char buf[254];
  3123. snprintf(buf, sizeof(buf)-1,"Distance %f %f diff %f\n", fDistanceCpu, fDistanceGpu, fDistanceCpu-fDistanceGpu);
  3124. OutputDebugString(buf);
  3125. nCountDown = 100;
  3126. }
  3127. #endif
  3128. return 1;
  3129. }
  3130. return 0;
  3131. }
  3132. #endif
  3133. #undef S
  3134. #ifdef _MSC_VER
  3135. #pragma warning(pop)
  3136. #endif
  3137. #endif
  3138. #endif
  3139. #ifdef MICROPROFILE_EMBED_HTML
  3140. #include "microprofile_html.h"
  3141. #endif