| 1 | // Copyright 2008 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/Timer.h" |
| 5 | |
| 6 | #include <chrono> |
| 7 | #include <thread> |
| 8 | #include "Common/CommonFuncs.h" |
| 9 | |
| 10 | #ifdef _WIN32 |
| 11 | #include <Windows.h> |
| 12 | #include <timeapi.h> |
| 13 | #endif |
| 14 | |
| 15 | #include "Common/CommonTypes.h" |
| 16 | #include "Common/Logging/Log.h" |
| 17 | |
| 18 | namespace Common |
| 19 | { |
| 20 | template <typename Clock, typename Duration> |
| 21 | static typename Clock::rep time_now() |
| 22 | { |
| 23 | return std::chrono::time_point_cast<Duration>(Clock::now()).time_since_epoch().count(); |
| 24 | } |
| 25 | |
| 26 | template <typename Duration> |
| 27 | static auto steady_time_now() |
| 28 | { |
| 29 | return time_now<std::chrono::steady_clock, Duration>(); |
| 30 | } |
| 31 | |
| 32 | u64 Timer::NowUs() |
| 33 | { |
| 34 | return steady_time_now<std::chrono::microseconds>(); |
| 35 | } |
| 36 | |
| 37 | u64 Timer::NowMs() |
| 38 | { |
| 39 | return steady_time_now<std::chrono::milliseconds>(); |
| 40 | } |
| 41 | |
| 42 | void Timer::Start() |
| 43 | { |
| 44 | m_start_ms = NowMs(); |
| 45 | m_end_ms = 0; |
| 46 | m_running = true; |
| 47 | } |
| 48 | |
| 49 | void Timer::StartWithOffset(u64 offset) |
| 50 | { |
| 51 | Start(); |
| 52 | m_start_ms -= offset; |
| 53 | } |
| 54 | |
| 55 | void Timer::Stop() |
| 56 | { |
| 57 | m_end_ms = NowMs(); |
| 58 | m_running = false; |
| 59 | } |
| 60 | |
| 61 | u64 Timer::ElapsedMs() const |
| 62 | { |
| 63 | const u64 end = m_running ? NowMs() : m_end_ms; |
| 64 | // Can handle up to 1 rollover event (underflow produces correct result) |
| 65 | // If Start() has never been called, will return 0 |
| 66 | return end - m_start_ms; |
| 67 | } |
| 68 | |
| 69 | u64 Timer::GetLocalTimeSinceJan1970() |
| 70 | { |
| 71 | #ifdef _MSC_VER |
| 72 | std::chrono::zoned_seconds seconds( |
| 73 | std::chrono::current_zone(), |
| 74 | std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now())); |
| 75 | return seconds.get_local_time().time_since_epoch().count(); |
| 76 | #else |
| 77 | time_t sysTime, tzDiff, tzDST; |
| 78 | time(&sysTime); |
| 79 | tm* gmTime = localtime(&sysTime); |
| 80 | |
| 81 | // Account for DST where needed |
| 82 | if (gmTime->tm_isdst == 1) |
| 83 | tzDST = 3600; |
| 84 | else |
| 85 | tzDST = 0; |
| 86 | |
| 87 | // Lazy way to get local time in sec |
| 88 | gmTime = gmtime(&sysTime); |
| 89 | tzDiff = sysTime - mktime(gmTime); |
| 90 | |
| 91 | return static_cast<u64>(sysTime + tzDiff + tzDST); |
| 92 | #endif |
| 93 | } |
| 94 | |
| 95 | // This is requested by Timer::IncreaseResolution on Windows. |
| 96 | // On Linux/other we hope/assume we already have 1ms scheduling granularity. |
| 97 | static constexpr int TIMER_RESOLUTION_MS = 1; |
| 98 | |
| 99 | void Timer::IncreaseResolution() |
| 100 | { |
| 101 | #ifdef _WIN32 |
| 102 | // Disable execution speed and timer resolution throttling process-wide. |
| 103 | // This mainly will keep Dolphin marked as high performance if it's in the background. The OS |
| 104 | // should make it high performance if it's in the foreground anyway (or for some specific |
| 105 | // threads e.g. audio). |
| 106 | // This is best-effort (i.e. the call may fail on older versions of Windows, where such throttling |
| 107 | // doesn't exist, anyway), and we don't bother reverting once set. |
| 108 | // This adjusts behavior on CPUs with "performance" and "efficiency" cores |
| 109 | PROCESS_POWER_THROTTLING_STATE PowerThrottling{}; |
| 110 | PowerThrottling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION; |
| 111 | PowerThrottling.ControlMask = |
| 112 | PROCESS_POWER_THROTTLING_EXECUTION_SPEED | PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION; |
| 113 | PowerThrottling.StateMask = 0; |
| 114 | SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &PowerThrottling, |
| 115 | sizeof(PowerThrottling)); |
| 116 | |
| 117 | // Not actually sure how useful this is these days.. :') |
| 118 | timeBeginPeriod(TIMER_RESOLUTION_MS); |
| 119 | #endif |
| 120 | } |
| 121 | |
| 122 | void Timer::RestoreResolution() |
| 123 | { |
| 124 | #ifdef _WIN32 |
| 125 | timeEndPeriod(TIMER_RESOLUTION_MS); |
| 126 | #endif |
| 127 | } |
| 128 | |
| 129 | PrecisionTimer::PrecisionTimer() |
| 130 | { |
| 131 | #if defined(_WIN32) |
| 132 | // "TIMER_HIGH_RESOLUTION" requires Windows 10, version 1803, and later. |
| 133 | m_timer_handle = |
| 134 | CreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); |
| 135 | |
| 136 | if (m_timer_handle == NULL) |
| 137 | { |
| 138 | ERROR_LOG_FMT(COMMON, "CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: Error:{}", GetLastError()); |
| 139 | |
| 140 | // Create a normal timer if "HIGH_RESOLUTION" isn't available. |
| 141 | m_timer_handle = CreateWaitableTimerExW(NULL, NULL, 0, TIMER_ALL_ACCESS); |
| 142 | if (m_timer_handle == NULL) |
| 143 | ERROR_LOG_FMT(COMMON, "CreateWaitableTimerExW: Error:{}", GetLastError()); |
| 144 | } |
| 145 | #endif |
| 146 | } |
| 147 | |
| 148 | PrecisionTimer::~PrecisionTimer() |
| 149 | { |
| 150 | #if defined(_WIN32) |
| 151 | CloseHandle(m_timer_handle); |
| 152 | #endif |
| 153 | } |
| 154 | |
| 155 | void PrecisionTimer::SleepUntil(Clock::time_point target) |
| 156 | { |
| 157 | constexpr auto SPIN_TIME = |
| 158 | std::chrono::milliseconds{TIMER_RESOLUTION_MS} + std::chrono::microseconds{20}; |
| 159 | |
| 160 | #if defined(_WIN32) |
| 161 | while (true) |
| 162 | { |
| 163 | // SetWaitableTimerEx takes time in "100 nanosecond intervals". |
| 164 | using TimerDuration = std::chrono::duration<LONGLONG, std::ratio<100, std::nano::den>::type>; |
| 165 | |
| 166 | // Apparently waiting longer than the timer resolution gives terrible accuracy. |
| 167 | // We'll wait in steps of 95% of the time period. |
| 168 | constexpr auto MAX_TICKS = |
| 169 | duration_cast<TimerDuration>(std::chrono::milliseconds{TIMER_RESOLUTION_MS}) * 95 / 100; |
| 170 | |
| 171 | const auto wait_time = target - Clock::now() - SPIN_TIME; |
| 172 | const auto ticks = std::min(duration_cast<TimerDuration>(wait_time), MAX_TICKS).count(); |
| 173 | if (ticks <= 0) |
| 174 | break; |
| 175 | |
| 176 | const LARGE_INTEGER due_time{.QuadPart = -ticks}; |
| 177 | SetWaitableTimerEx(m_timer_handle, &due_time, 0, NULL, NULL, NULL, 0); |
| 178 | WaitForSingleObject(m_timer_handle, INFINITE); |
| 179 | } |
| 180 | #else |
| 181 | // Sleeping on Linux generally isn't as terrible as it is on Windows. |
| 182 | std::this_thread::sleep_until(target - SPIN_TIME); |
| 183 | #endif |
| 184 | |
| 185 | // Spin for the remaining time. |
| 186 | while (Clock::now() < target) |
| 187 | { |
| 188 | #if defined(_WIN32) |
| 189 | YieldProcessor(); |
| 190 | #else |
| 191 | std::this_thread::yield(); |
| 192 | #endif |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // Results are appropriately slewed on Linux, but not on Windows, macOS, or FreeBSD. |
| 197 | // Clocks with that functionality seem to not be available there. |
| 198 | auto SteadyAwakeClock::now() -> time_point |
| 199 | { |
| 200 | #if defined(_WIN32) |
| 201 | // The count is system time "in units of 100 nanoseconds". |
| 202 | using InterruptDuration = std::chrono::duration<ULONGLONG, std::ratio<100, std::nano::den>::type>; |
| 203 | |
| 204 | ULONGLONG interrupt_time{}; |
| 205 | if (!QueryUnbiasedInterruptTime(&interrupt_time)) |
| 206 | ERROR_LOG_FMT(COMMON, "QueryUnbiasedInterruptTime"); |
| 207 | |
| 208 | return time_point{InterruptDuration{interrupt_time}}; |
| 209 | #else |
| 210 | // Note that Linux's CLOCK_MONOTONIC "does not count time that the system is suspended". |
| 211 | // This is in contrast to the behavior on macOS and FreeBSD. |
| 212 | static constexpr auto clock_id = |
| 213 | #if defined(__linux__) |
| 214 | CLOCK_MONOTONIC; |
| 215 | #elif defined(__APPLE__) |
| 216 | CLOCK_UPTIME_RAW; |
| 217 | #else |
| 218 | CLOCK_UPTIME; |
| 219 | #endif |
| 220 | |
| 221 | timespec ts{}; |
| 222 | if (clock_gettime(clock_id, &ts) != 0) |
| 223 | ERROR_LOG_FMT(COMMON, "clock_gettime: {}", LastStrerrorString()); |
| 224 | |
| 225 | return time_point{std::chrono::seconds{ts.tv_sec} + std::chrono::nanoseconds{ts.tv_nsec}}; |
| 226 | #endif |
| 227 | } |
| 228 | |
| 229 | } // Namespace Common |