From d3f14efbbdb7fc07f74b39bee00f58749f0391e8 Mon Sep 17 00:00:00 2001 From: Ari Vuollet Date: Sun, 21 May 2023 20:22:56 +0300 Subject: [PATCH] _adaptive sleep --- Source/Engine/Engine/Engine.cpp | 41 ++++++++++++++++--- .../Engine/Platform/Win32/Win32Platform.cpp | 9 ++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/Source/Engine/Engine/Engine.cpp b/Source/Engine/Engine/Engine.cpp index 20063ca0f..f50be408b 100644 --- a/Source/Engine/Engine/Engine.cpp +++ b/Source/Engine/Engine/Engine.cpp @@ -165,16 +165,41 @@ int32 Engine::Main(const Char* cmdLine) while (!ShouldExit()) { // Reduce CPU usage by introducing idle time if the engine is running very fast and has enough time to spend - if ((useSleep && Time::UpdateFPS > ZeroTolerance) || !Platform::GetHasFocus()) + if ((useSleep && Time::UpdateFPS > ZeroTolerance && Time::PhysicsFPS > ZeroTolerance && Time::DrawFPS > ZeroTolerance)) { double nextTick = Time::GetNextTick(); double timeToTick = nextTick - Platform::GetTimeSeconds(); - // Sleep less than needed, some platforms may sleep slightly more than requested - if (timeToTick > 0.002) + if (timeToTick > 0) { - PROFILE_CPU_NAMED("Idle"); - Platform::Sleep(1); + // Sleep less than needed, some platforms may sleep slightly more than requested + static double adaptiveMinSleep = 0.00001; + if (timeToTick > adaptiveMinSleep) + { + PROFILE_CPU_NAMED("Idle"); + while (timeToTick > adaptiveMinSleep) + { + Platform::Sleep(1); + //Platform::Sleep(-1111); + timeToTick = nextTick - Platform::GetTimeSeconds(); + } + } + + if (timeToTick < 0) + { + adaptiveMinSleep += -timeToTick * 0.15; + //Log::Logger::Write(LogType::Info, TEXT("{0}, adaptive: {1}"), -timeToTick * 1000.0, adaptiveMinSleep); + } + else + { + adaptiveMinSleep -= 0.000000001; + PROFILE_CPU_NAMED("IdleBusyLoop"); + while (timeToTick > 0) + { + Platform::Sleep(-1111); + timeToTick = nextTick - Platform::GetTimeSeconds(); + } + } } } @@ -218,6 +243,12 @@ int32 Engine::Main(const Char* cmdLine) Time::OnEndDraw(); FrameMark; } + + /*{ + PROFILE_CPU_NAMED("CollectResults"); + // Collect physics simulation results (does nothing if Simulate hasn't been called in the previous loop step) + Physics::CollectResults(); + }*/ } // Call on exit event diff --git a/Source/Engine/Platform/Win32/Win32Platform.cpp b/Source/Engine/Platform/Win32/Win32Platform.cpp index d46706621..0dbf71cab 100644 --- a/Source/Engine/Platform/Win32/Win32Platform.cpp +++ b/Source/Engine/Platform/Win32/Win32Platform.cpp @@ -370,6 +370,15 @@ void Win32Platform::SetThreadAffinityMask(uint64 affinityMask) void Win32Platform::Sleep(int32 milliseconds) { + if (milliseconds < 0) + { + ::SwitchToThread(); + return; + } + + //::Sleep(milliseconds); + //return; + static thread_local HANDLE timer = NULL; if (timer == NULL) {