microprofile.h 120 KB

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