microprofile.h 120 KB

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