From 8ea01a571be073be00f8a77150f3d62ef5600b52 Mon Sep 17 00:00:00 2001 From: Nicolas James Date: Thu, 12 Mar 2026 20:42:37 +1100 Subject: Fix potential clock domain mismatch when using chrono::now() --- src/device_context.cc | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'src/device_context.cc') diff --git a/src/device_context.cc b/src/device_context.cc index 0f606b5..99a4979 100644 --- a/src/device_context.cc +++ b/src/device_context.cc @@ -1,6 +1,7 @@ #include "device_context.hh" #include "queue_context.hh" +#include #include #include @@ -36,6 +37,17 @@ DeviceContext::Clock::Clock(const DeviceContext& context) : device(context) { DeviceContext::Clock::~Clock() {} +DeviceContext::Clock::time_point_t DeviceContext::Clock::now() { + + auto ts = timespec{}; + if (clock_gettime(CLOCK_MONOTONIC, &ts)) { + throw errno; + } + + return time_point_t{std::chrono::seconds{ts.tv_sec} + + std::chrono::nanoseconds{ts.tv_nsec}}; +} + void DeviceContext::Clock::calibrate() { const auto infos = std::vector{ {VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, nullptr, @@ -75,14 +87,10 @@ DeviceContext::Clock::ticks_to_time(const std::uint64_t& ticks) const { return is_negative ? -signed_abs_diff : signed_abs_diff; }(); - // This will have issues because std::chrono::steady_clock::now(), which - // we use for cpu time, may not be on the same time domain what was returned - // by GetCalibratedTimestamps. It would be more robust to use the posix - // gettime that vulkan guarantees it can be compared to instead. - const auto diff_nsec = static_cast(static_cast(diff) * ns_tick + 0.5); - const auto delta = std::chrono::nanoseconds(this->host_ns + diff_nsec); + const auto delta = std::chrono::nanoseconds( + this->host_ns + static_cast(diff_nsec)); return time_point_t{delta}; } -- cgit v1.2.3