From 4ba83301948970d007ddaaba3df0c3f1697040ed Mon Sep 17 00:00:00 2001 From: emeric Date: Sun, 31 Mar 2024 13:07:02 +0200 Subject: [PATCH] Tracing: use only lower 32bits for thread, to make capture compatible with perfetto UI --- src/libs/core/impl/TraceLogger.cpp | 25 +++++++++++++++++++++++-- src/libs/core/impl/TraceLogger.hpp | 2 ++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/libs/core/impl/TraceLogger.cpp b/src/libs/core/impl/TraceLogger.cpp index 20d4b1c2..614713ae 100644 --- a/src/libs/core/impl/TraceLogger.cpp +++ b/src/libs/core/impl/TraceLogger.cpp @@ -141,7 +141,7 @@ namespace lms::core::tracing os << "\t\t{ "; os << "\"name\" : \"thread_name\", "; os << "\"pid\" : 1, "; - os << "\"tid\" : " << threadId << ", "; + os << "\"tid\" : " << toTraceThreadId(threadId) << ", "; os << "\"ph\" : \"M\", "; os << "\"args\" : { \"name\" : \"" + threadName + "\" }"; os << " }"; @@ -171,7 +171,7 @@ namespace lms::core::tracing os << "\"name\" : \"" << event.name.c_str() << "\", "; os << "\"cat\" : \"" << event.category.c_str() << "\", "; os << "\"pid\": 1, "; - os << "\"tid\" : " << event.threadId << ", "; + os << "\"tid\" : " << toTraceThreadId(event.threadId) << ", "; os << "\"ts\" : " << std::fixed << std::setprecision(3) << std::chrono::duration_cast(event.start - _start).count() << ", "; os << "\"dur\" : " << std::fixed << std::setprecision(3) << std::chrono::duration_cast(event.duration).count() << ", "; os << "\"ph\" : \"X\""; @@ -198,4 +198,25 @@ namespace lms::core::tracing std::scoped_lock lock{ _threadNameMutex }; _threadNames.emplace(id, threadName); } + + std::uint32_t TraceLogger::toTraceThreadId(std::thread::id threadId) const + { + { + auto it{ _cachedTraceThreadIds.find(threadId) }; + if (it != std::cend(_cachedTraceThreadIds)) + return it->second; + } + + // Pefetto UI does not accept 64bits thread ids + std::ostringstream oss; + oss << threadId; + + std::istringstream iss{ oss.str() }; + std::uint64_t id; + iss >> id; + + const std::uint32_t res{ static_cast(id) }; + _cachedTraceThreadIds.emplace(threadId, res); + return res; + } } \ No newline at end of file diff --git a/src/libs/core/impl/TraceLogger.hpp b/src/libs/core/impl/TraceLogger.hpp index 9addf082..17e0cea7 100644 --- a/src/libs/core/impl/TraceLogger.hpp +++ b/src/libs/core/impl/TraceLogger.hpp @@ -42,6 +42,7 @@ namespace lms::core::tracing void write(const CompleteEvent& event) override; void dumpCurrentBuffer(std::ostream& os) override; void setThreadName(std::thread::id id, std::string_view threadName) override; + std::uint32_t toTraceThreadId(std::thread::id threadId) const; static constexpr std::size_t BufferSize{ 32 * 1024 }; @@ -64,6 +65,7 @@ namespace lms::core::tracing std::mutex _threadNameMutex; std::unordered_map _threadNames; + mutable std::unordered_map _cachedTraceThreadIds; std::mutex _mutex; std::deque _freeBuffers;