diff --git a/Utilities/Thread.cpp b/Utilities/Thread.cpp index 1e84c7c2df..6b2789daf7 100644 --- a/Utilities/Thread.cpp +++ b/Utilities/Thread.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #endif #include "sync.h" @@ -1851,6 +1852,36 @@ void thread_ctrl::notify() } } +u64 thread_ctrl::get_cycles() +{ + u64 cycles; + +#ifdef _WIN32 + if (QueryThreadCycleTime((HANDLE)m_thread.load(), &cycles)) + { +#else + struct timespec thread_time; + if (!clock_gettime(CLOCK_THREAD_CPUTIME_ID, &thread_time)) + { + cycles = static_cast(thread_time.tv_sec) * 1'000'000'000 + thread_time.tv_nsec; +#endif + // Report 0 the first time this function is called + if (m_cycles == 0) + { + m_cycles = cycles; + return 0; + } + + const auto diff_cycles = cycles - m_cycles; + m_cycles = cycles; + return diff_cycles; + } + else + { + return m_cycles; + } +} + void thread_ctrl::test() { const auto _this = g_tls_this_thread; diff --git a/Utilities/Thread.h b/Utilities/Thread.h index 11cb504253..75c6ea3dda 100644 --- a/Utilities/Thread.h +++ b/Utilities/Thread.h @@ -138,6 +138,9 @@ class thread_ctrl final // Fixed name std::string m_name; + // CPU cycles thread has run for + u64 m_cycles{0}; + // Start thread static void start(const std::shared_ptr&, task_stack); @@ -172,6 +175,15 @@ public: return m_name; } + // Get CPU cycles since last time this function was called. First call returns 0. + u64 get_cycles(); + + // Get platform-specific thread handle + std::uintptr_t get_native_handle() const + { + return m_thread.load(); + } + // Get exception std::exception_ptr get_exception() const;