CoreTracer.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Core/CoreTracer.h>
  6. #include <AnKi/Util/DynamicArray.h>
  7. #include <AnKi/Util/Tracer.h>
  8. #include <AnKi/Math/Functions.h>
  9. #include <ctime>
  10. namespace anki
  11. {
  12. static void getSpreadsheetColumnName(U32 column, Array<char, 3>& arr)
  13. {
  14. U32 major = column / 26;
  15. U32 minor = column % 26;
  16. if(major)
  17. {
  18. arr[0] = char('A' + (major - 1));
  19. arr[1] = char('A' + minor);
  20. }
  21. else
  22. {
  23. arr[0] = char('A' + minor);
  24. arr[1] = '\0';
  25. }
  26. arr[2] = '\0';
  27. }
  28. class CoreTracer::ThreadWorkItem : public IntrusiveListEnabled<ThreadWorkItem>
  29. {
  30. public:
  31. DynamicArrayAuto<TracerEvent> m_events;
  32. DynamicArrayAuto<TracerCounter> m_counters;
  33. ThreadId m_tid;
  34. U64 m_frame;
  35. ThreadWorkItem(GenericMemoryPoolAllocator<U8>& alloc)
  36. : m_events(alloc)
  37. , m_counters(alloc)
  38. {
  39. }
  40. };
  41. class CoreTracer::PerFrameCounters : public IntrusiveListEnabled<PerFrameCounters>
  42. {
  43. public:
  44. DynamicArrayAuto<TracerCounter> m_counters;
  45. U64 m_frame;
  46. PerFrameCounters(GenericMemoryPoolAllocator<U8>& alloc)
  47. : m_counters(alloc)
  48. {
  49. }
  50. };
  51. CoreTracer::CoreTracer()
  52. : m_thread("Tracer")
  53. {
  54. }
  55. CoreTracer::~CoreTracer()
  56. {
  57. // Stop thread
  58. {
  59. LockGuard<Mutex> lock(m_mtx);
  60. m_quit = true;
  61. m_cvar.notifyOne();
  62. }
  63. Error err = m_thread.join();
  64. (void)err;
  65. // Finalize trace file
  66. if(m_traceJsonFile.isOpen())
  67. {
  68. err = m_traceJsonFile.writeText("{}\n]\n");
  69. }
  70. // Write counter file
  71. err = writeCountersForReal();
  72. // Cleanup
  73. while(!m_frameCounters.isEmpty())
  74. {
  75. PerFrameCounters* frame = m_frameCounters.popBack();
  76. m_alloc.deleteInstance(frame);
  77. }
  78. while(!m_workItems.isEmpty())
  79. {
  80. ThreadWorkItem* item = m_workItems.popBack();
  81. m_alloc.deleteInstance(item);
  82. }
  83. for(String& s : m_counterNames)
  84. {
  85. s.destroy(m_alloc);
  86. }
  87. m_counterNames.destroy(m_alloc);
  88. // Destroy the tracer
  89. TracerSingleton::destroy();
  90. }
  91. Error CoreTracer::init(GenericMemoryPoolAllocator<U8> alloc, CString directory)
  92. {
  93. TracerSingleton::init(alloc);
  94. const Bool enableTracer = getenv("ANKI_CORE_TRACER_ENABLED") && getenv("ANKI_CORE_TRACER_ENABLED")[0] == '1';
  95. TracerSingleton::get().setEnabled(enableTracer);
  96. ANKI_CORE_LOGI("Tracing is %s from the beginning", (enableTracer) ? "enabled" : "disabled");
  97. m_alloc = alloc;
  98. m_thread.start(this, [](ThreadCallbackInfo& info) -> Error {
  99. return static_cast<CoreTracer*>(info.m_userData)->threadWorker();
  100. });
  101. std::time_t t = std::time(nullptr);
  102. std::tm* tm = std::localtime(&t);
  103. StringAuto fname(m_alloc);
  104. fname.sprintf("%s/%d%02d%02d-%02d%02d_", directory.cstr(), tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  105. tm->tm_hour, tm->tm_min);
  106. ANKI_CHECK(m_traceJsonFile.open(StringAuto(alloc).sprintf("%strace.json", fname.cstr()), FileOpenFlag::WRITE));
  107. ANKI_CHECK(m_traceJsonFile.writeText("[\n"));
  108. ANKI_CHECK(m_countersCsvFile.open(StringAuto(alloc).sprintf("%scounters.csv", fname.cstr()), FileOpenFlag::WRITE));
  109. return Error::NONE;
  110. }
  111. Error CoreTracer::threadWorker()
  112. {
  113. Error err = Error::NONE;
  114. Bool quit = false;
  115. while(!err && !quit)
  116. {
  117. ThreadWorkItem* item = nullptr;
  118. // Get some work
  119. {
  120. // Wait for something
  121. LockGuard<Mutex> lock(m_mtx);
  122. while(m_workItems.isEmpty() && !m_quit)
  123. {
  124. m_cvar.wait(m_mtx);
  125. }
  126. // Get some work
  127. if(!m_workItems.isEmpty())
  128. {
  129. item = m_workItems.popFront();
  130. }
  131. else if(m_quit)
  132. {
  133. quit = true;
  134. }
  135. }
  136. // Do some work using the frame and delete it
  137. if(item)
  138. {
  139. err = writeEvents(*item);
  140. if(!err)
  141. {
  142. gatherCounters(*item);
  143. }
  144. m_alloc.deleteInstance(item);
  145. }
  146. }
  147. return err;
  148. }
  149. Error CoreTracer::writeEvents(ThreadWorkItem& item)
  150. {
  151. // First sort them to fix overlaping in chrome
  152. std::sort(item.m_events.getBegin(), item.m_events.getEnd(), [](const TracerEvent& a, TracerEvent& b) {
  153. return (a.m_start != b.m_start) ? a.m_start < b.m_start : a.m_duration > b.m_duration;
  154. });
  155. // Write events
  156. for(const TracerEvent& event : item.m_events)
  157. {
  158. const I64 startMicroSec = I64(event.m_start * 1000000.0);
  159. const I64 durMicroSec = I64(event.m_duration * 1000000.0);
  160. // Do a hack
  161. const ThreadId tid = (event.m_name == "GPU_TIME") ? 1 : item.m_tid;
  162. ANKI_CHECK(m_traceJsonFile.writeText("{\"name\": \"%s\", \"cat\": \"PERF\", \"ph\": \"X\", "
  163. "\"pid\": 1, \"tid\": %llu, \"ts\": %lld, \"dur\": %lld},\n",
  164. event.m_name.cstr(), tid, startMicroSec, durMicroSec));
  165. }
  166. // Store counters
  167. // TODO
  168. return Error::NONE;
  169. }
  170. void CoreTracer::gatherCounters(ThreadWorkItem& item)
  171. {
  172. // Sort
  173. std::sort(item.m_counters.getBegin(), item.m_counters.getEnd(),
  174. [](const TracerCounter& a, const TracerCounter& b) { return a.m_name < b.m_name; });
  175. // Merge same
  176. DynamicArrayAuto<TracerCounter> mergedCounters(m_alloc);
  177. for(U32 i = 0; i < item.m_counters.getSize(); ++i)
  178. {
  179. if(mergedCounters.getSize() == 0 || mergedCounters.getBack().m_name != item.m_counters[i].m_name)
  180. {
  181. // New
  182. mergedCounters.emplaceBack(item.m_counters[i]);
  183. }
  184. else
  185. {
  186. // Merge
  187. mergedCounters.getBack().m_value += item.m_counters[i].m_value;
  188. }
  189. }
  190. ANKI_ASSERT(mergedCounters.getSize() > 0 && mergedCounters.getSize() <= item.m_counters.getSize());
  191. // Add missing counter names
  192. Bool addedCounterName = false;
  193. for(U32 i = 0; i < mergedCounters.getSize(); ++i)
  194. {
  195. const TracerCounter& counter = mergedCounters[i];
  196. Bool found = false;
  197. for(const String& name : m_counterNames)
  198. {
  199. if(name == counter.m_name)
  200. {
  201. found = true;
  202. break;
  203. }
  204. }
  205. if(!found)
  206. {
  207. m_counterNames.emplaceBack(m_alloc, m_alloc, counter.m_name);
  208. addedCounterName = true;
  209. }
  210. }
  211. if(addedCounterName)
  212. {
  213. std::sort(m_counterNames.getBegin(), m_counterNames.getEnd());
  214. }
  215. // Get a per-frame structure
  216. if(m_frameCounters.isEmpty() || m_frameCounters.getBack().m_frame != item.m_frame)
  217. {
  218. // Create new frame
  219. PerFrameCounters* newPerFrame = m_alloc.newInstance<PerFrameCounters>(m_alloc);
  220. newPerFrame->m_counters = std::move(mergedCounters);
  221. newPerFrame->m_frame = item.m_frame;
  222. m_frameCounters.pushBack(newPerFrame);
  223. }
  224. else
  225. {
  226. // Merge counters to existing frame
  227. PerFrameCounters& frame = m_frameCounters.getBack();
  228. ANKI_ASSERT(frame.m_frame == item.m_frame);
  229. for(const TracerCounter& newCounter : mergedCounters)
  230. {
  231. Bool found = false;
  232. for(TracerCounter& existingCounter : frame.m_counters)
  233. {
  234. if(newCounter.m_name == existingCounter.m_name)
  235. {
  236. existingCounter.m_value += newCounter.m_value;
  237. found = true;
  238. break;
  239. }
  240. }
  241. if(!found)
  242. {
  243. frame.m_counters.emplaceBack(newCounter);
  244. }
  245. }
  246. }
  247. }
  248. void CoreTracer::flushFrame(U64 frame)
  249. {
  250. struct Ctx
  251. {
  252. U64 m_frame;
  253. CoreTracer* m_self;
  254. };
  255. Ctx ctx;
  256. ctx.m_frame = frame;
  257. ctx.m_self = this;
  258. TracerSingleton::get().flush(
  259. [](void* ud, ThreadId tid, ConstWeakArray<TracerEvent> events, ConstWeakArray<TracerCounter> counters) {
  260. Ctx& ctx = *static_cast<Ctx*>(ud);
  261. CoreTracer& self = *ctx.m_self;
  262. ThreadWorkItem* item = self.m_alloc.newInstance<ThreadWorkItem>(self.m_alloc);
  263. item->m_tid = tid;
  264. item->m_frame = ctx.m_frame;
  265. if(events.getSize() > 0)
  266. {
  267. item->m_events.create(events.getSize());
  268. memcpy(&item->m_events[0], &events[0], events.getSizeInBytes());
  269. }
  270. if(counters.getSize() > 0)
  271. {
  272. item->m_counters.create(counters.getSize());
  273. memcpy(&item->m_counters[0], &counters[0], counters.getSizeInBytes());
  274. }
  275. LockGuard<Mutex> lock(self.m_mtx);
  276. self.m_workItems.pushBack(item);
  277. self.m_cvar.notifyOne();
  278. },
  279. &ctx);
  280. }
  281. Error CoreTracer::writeCountersForReal()
  282. {
  283. if(!m_countersCsvFile.isOpen() || m_frameCounters.getSize() == 0)
  284. {
  285. return Error::NONE;
  286. }
  287. // Write the header
  288. ANKI_CHECK(m_countersCsvFile.writeText("Frame"));
  289. for(U32 i = 0; i < m_counterNames.getSize(); ++i)
  290. {
  291. ANKI_CHECK(m_countersCsvFile.writeText(",%s", m_counterNames[i].cstr()));
  292. }
  293. ANKI_CHECK(m_countersCsvFile.writeText("\n"));
  294. // Write each frame
  295. for(const PerFrameCounters& frame : m_frameCounters)
  296. {
  297. ANKI_CHECK(m_countersCsvFile.writeText("%llu", frame.m_frame));
  298. for(U32 j = 0; j < m_counterNames.getSize(); ++j)
  299. {
  300. // Find value
  301. U64 value = 0;
  302. for(const TracerCounter& counter : frame.m_counters)
  303. {
  304. if(counter.m_name == m_counterNames[j])
  305. {
  306. value = counter.m_value;
  307. break;
  308. }
  309. }
  310. ANKI_CHECK(m_countersCsvFile.writeText(",%llu", value));
  311. }
  312. ANKI_CHECK(m_countersCsvFile.writeText("\n"));
  313. }
  314. // Write some statistics
  315. Array<const char*, 2> funcs = {"SUM", "AVERAGE"};
  316. for(const char* func : funcs)
  317. {
  318. ANKI_CHECK(m_countersCsvFile.writeText(func));
  319. for(U32 i = 0; i < m_frameCounters.getSize(); ++i)
  320. {
  321. Array<char, 3> columnName;
  322. getSpreadsheetColumnName(i + 1, columnName);
  323. ANKI_CHECK(m_countersCsvFile.writeText(",=%s(%s2:%s%u)", func, &columnName[0], &columnName[0],
  324. m_frameCounters.getSize() + 1));
  325. }
  326. ANKI_CHECK(m_countersCsvFile.writeText("\n"));
  327. }
  328. return Error::NONE;
  329. }
  330. } // end namespace anki