From 09fc46d306ec55a8830dbb78e8304901fd259722 Mon Sep 17 00:00:00 2001 From: zhenyan121 <3367366583@qq.com> Date: Fri, 26 Jun 2026 22:00:36 +0800 Subject: [PATCH] refactor(gameplay): use steady clock and sleep_until for tick loop timing --- src/gameplay/client_world.cpp | 14 +++++++------- src/gameplay/server_world.cpp | 13 +++++++------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/gameplay/client_world.cpp b/src/gameplay/client_world.cpp index 8e07b6f..08e3c55 100644 --- a/src/gameplay/client_world.cpp +++ b/src/gameplay/client_world.cpp @@ -289,17 +289,17 @@ void ClientWorld::hot_reload() { void ClientWorld::client_run(std::stop_token stoken) { Logger::info("Client Thread Started"); - while (!stoken.stop_requested()) { - auto t1 = system_clock::now(); + using Clock = std::chrono::steady_clock; + constexpr auto TICK = std::chrono::milliseconds(DEFAULT_PER_TICK_TIME); + + auto next = Clock::now(); + while (!stoken.stop_requested()) { + next += TICK; for (auto& x : m_timers) { x.second.update(); } - - auto t2 = system_clock::now(); - auto dt = duration_cast(t2 - t1); - auto st = std::max(dt, milliseconds(DEFAULT_PER_TICK_TIME) - dt); - std::this_thread::sleep_for(st); + std::this_thread::sleep_until(next); } } diff --git a/src/gameplay/server_world.cpp b/src/gameplay/server_world.cpp index 9b11da0..6845c3b 100644 --- a/src/gameplay/server_world.cpp +++ b/src/gameplay/server_world.cpp @@ -299,18 +299,19 @@ void ServerWorld::stop_thread_pool() { void ServerWorld::serever_run(std::stop_token stoken) { Logger::info("Server Thread Started!"); - while (!stoken.stop_requested()) { - auto t1 = system_clock::now(); + using Clock = std::chrono::steady_clock; + constexpr auto TICK = std::chrono::milliseconds(DEFAULT_PER_TICK_TIME); + + auto next = Clock::now(); + while (!stoken.stop_requested()) { + next += TICK; if (m_tick_running) { ++m_game_ticks; m_day_tick = (m_day_tick + 1) % DAY_TIME; } update(); - auto t2 = system_clock::now(); - auto dt = duration_cast(t2 - t1); - auto st = std::max(dt, milliseconds(m_per_tick_time) - dt); - std::this_thread::sleep_for(st); + std::this_thread::sleep_until(next); } Logger::info("Server Thread Stopped!"); }