Merge pull request #10872 from shuffle2/timer

Timer improvements
This commit is contained in:
Mai
2022-08-03 14:30:29 -04:00
committed by GitHub
24 changed files with 234 additions and 326 deletions

View File

@ -99,6 +99,7 @@ static bool s_wants_determinism;
// Declarations and definitions
static Common::Timer s_timer;
static u64 s_timer_offset;
static std::atomic<u32> s_drawn_frame;
static std::atomic<u32> s_drawn_video;
@ -271,8 +272,6 @@ void Stop() // - Hammertime!
s_is_stopping = true;
s_timer.Stop();
CallOnStateChangedCallbacks(State::Stopping);
// Dump left over jobs
@ -662,21 +661,18 @@ void SetState(State state)
CPU::EnableStepping(true); // Break
Wiimote::Pause();
ResetRumble();
s_timer.Update();
s_timer_offset = s_timer.ElapsedMs();
break;
case State::Running:
{
CPU::EnableStepping(false);
Wiimote::Resume();
if (!s_timer.IsRunning())
{
s_timer.Start();
}
else
{
// Add time difference from the last pause
s_timer.AddTimeDifference();
}
// Restart timer, accounting for time that had elapsed between previous s_timer.Start() and
// emulator pause
s_timer.StartWithOffset(s_timer_offset);
s_timer_offset = 0;
break;
}
default:
PanicAlertFmt("Invalid state");
break;
@ -848,12 +844,12 @@ void RunOnCPUThread(std::function<void()> function, bool wait_for_completion)
void VideoThrottle()
{
// Update info per second
u32 ElapseTime = (u32)s_timer.GetTimeElapsed();
if ((ElapseTime >= 1000 && s_drawn_video.load() > 0) || s_frame_step)
u64 elapsed_ms = s_timer.ElapsedMs();
if ((elapsed_ms >= 1000 && s_drawn_video.load() > 0) || s_frame_step)
{
s_timer.Start();
UpdateTitle(ElapseTime);
UpdateTitle(elapsed_ms);
s_drawn_frame.store(0);
s_drawn_video.store(0);
@ -895,15 +891,15 @@ void Callback_NewField()
}
}
void UpdateTitle(u32 ElapseTime)
void UpdateTitle(u64 elapsed_ms)
{
if (ElapseTime == 0)
ElapseTime = 1;
if (elapsed_ms == 0)
elapsed_ms = 1;
float FPS = (float)(s_drawn_frame.load() * 1000.0 / ElapseTime);
float VPS = (float)(s_drawn_video.load() * 1000.0 / ElapseTime);
float FPS = (float)(s_drawn_frame.load() * 1000.0 / elapsed_ms);
float VPS = (float)(s_drawn_video.load() * 1000.0 / elapsed_ms);
float Speed = (float)(s_drawn_video.load() * (100 * 1000.0) /
(VideoInterface::GetTargetRefreshRate() * ElapseTime));
(VideoInterface::GetTargetRefreshRate() * elapsed_ms));
// Settings are shown the same for both extended and summary info
const std::string SSettings = fmt::format(

View File

@ -126,7 +126,7 @@ void OnFrameEnd();
void VideoThrottle();
void UpdateTitle(u32 ElapseTime);
void UpdateTitle(u64 elapsed_ms);
// Run a function as the CPU thread.
//

View File

@ -231,18 +231,18 @@ void DolphinAnalytics::InitializePerformanceSampling()
u64 wait_us =
PERFORMANCE_SAMPLING_INITIAL_WAIT_TIME_SECS * 1000000 +
Common::Random::GenerateValue<u64>() % (PERFORMANCE_SAMPLING_WAIT_TIME_JITTER_SECS * 1000000);
m_sampling_next_start_us = Common::Timer::GetTimeUs() + wait_us;
m_sampling_next_start_us = Common::Timer::NowUs() + wait_us;
}
bool DolphinAnalytics::ShouldStartPerformanceSampling()
{
if (Common::Timer::GetTimeUs() < m_sampling_next_start_us)
if (Common::Timer::NowUs() < m_sampling_next_start_us)
return false;
u64 wait_us =
PERFORMANCE_SAMPLING_INTERVAL_SECS * 1000000 +
Common::Random::GenerateValue<u64>() % (PERFORMANCE_SAMPLING_WAIT_TIME_JITTER_SECS * 1000000);
m_sampling_next_start_us = Common::Timer::GetTimeUs() + wait_us;
m_sampling_next_start_us = Common::Timer::NowUs() + wait_us;
return true;
}

View File

@ -286,7 +286,7 @@ static void StartReadInternal(bool copy_to_ram, u32 output_address, u64 dvd_offs
request.id = id;
request.time_started_ticks = CoreTiming::GetTicks();
request.realtime_started_us = Common::Timer::GetTimeUs();
request.realtime_started_us = Common::Timer::NowUs();
s_request_queue.Push(std::move(request));
s_request_queue_expanded.Set();
@ -336,7 +336,7 @@ static void FinishRead(u64 id, s64 cycles_late)
"Real time including delay: {} us. "
"Emulated time including delay: {} us.",
request.realtime_done_us - request.realtime_started_us,
Common::Timer::GetTimeUs() - request.realtime_started_us,
Common::Timer::NowUs() - request.realtime_started_us,
(CoreTiming::GetTicks() - request.time_started_ticks) /
(SystemTimers::GetTicksPerSecond() / 1000000));
@ -381,7 +381,7 @@ static void DVDThread()
if (!s_disc->Read(request.dvd_offset, request.length, buffer.data(), request.partition))
buffer.resize(0);
request.realtime_done_us = Common::Timer::GetTimeUs();
request.realtime_done_us = Common::Timer::NowUs();
s_result_queue.Push(ReadResult(std::move(request), std::move(buffer)));
s_result_queue_expanded.Set();

View File

@ -167,16 +167,19 @@ void PatchEngineCallback(u64 userdata, s64 cycles_late)
CoreTiming::ScheduleEvent(next_schedule, et_PatchEngine, cycles_pruned);
}
void ThrottleCallback(u64 last_time, s64 cyclesLate)
void ThrottleCallback(u64 deadline, s64 cyclesLate)
{
// Allow the GPU thread to sleep. Setting this flag here limits the wakeups to 1 kHz.
Fifo::GpuMaySleep();
u64 time = Common::Timer::GetTimeUs();
const u64 time = Common::Timer::NowUs();
s64 diff = last_time - time;
if (deadline == 0)
deadline = time;
const s64 diff = deadline - time;
const float emulation_speed = Config::Get(Config::MAIN_EMULATION_SPEED);
bool frame_limiter = emulation_speed > 0.0f && !Core::GetIsThrottlerTempDisabled();
const bool frame_limiter = emulation_speed > 0.0f && !Core::GetIsThrottlerTempDisabled();
u32 next_event = GetTicksPerSecond() / 1000;
{
@ -193,17 +196,19 @@ void ThrottleCallback(u64 last_time, s64 cyclesLate)
const s64 max_fallback = Config::Get(Config::MAIN_TIMING_VARIANCE) * 1000;
if (std::abs(diff) > max_fallback)
{
DEBUG_LOG_FMT(COMMON, "system too {}, {} ms skipped", diff < 0 ? "slow" : "fast",
DEBUG_LOG_FMT(COMMON, "system too {}, {} us skipped", diff < 0 ? "slow" : "fast",
std::abs(diff) - max_fallback);
last_time = time - max_fallback;
deadline = time - max_fallback;
}
else if (diff > 1000)
{
Common::SleepCurrentThread(diff / 1000);
s_time_spent_sleeping += Common::Timer::GetTimeUs() - time;
s_time_spent_sleeping += Common::Timer::NowUs() - time;
}
}
CoreTiming::ScheduleEvent(next_event - cyclesLate, et_Throttle, last_time + 1000);
// reschedule 1ms (possibly scaled by emulation_speed) into future on ppc
// add 1ms to the deadline
CoreTiming::ScheduleEvent(next_event - cyclesLate, et_Throttle, deadline + 1000);
}
} // namespace
@ -330,7 +335,7 @@ void Init()
CoreTiming::ScheduleEvent(VideoInterface::GetTicksPerHalfLine(), et_VI);
CoreTiming::ScheduleEvent(0, et_DSP);
CoreTiming::ScheduleEvent(GetAudioDMACallbackPeriod(), et_AudioDMA);
CoreTiming::ScheduleEvent(0, et_Throttle, Common::Timer::GetTimeUs());
CoreTiming::ScheduleEvent(0, et_Throttle, 0);
CoreTiming::ScheduleEvent(VideoInterface::GetTicksPerField(), et_PatchEngine);

View File

@ -33,24 +33,6 @@ enum
};
IPCReply GetSystemTime(const IOCtlVRequest& request)
{
if (!request.HasNumberOfValidVectors(0, 1))
{
return IPCReply(IPC_EINVAL);
}
if (request.io_vectors[0].size != 4)
{
return IPCReply(IPC_EINVAL);
}
const u32 milliseconds = Common::Timer::GetTimeMs();
Memory::Write_U32(milliseconds, request.io_vectors[0].address);
return IPCReply(IPC_SUCCESS);
}
IPCReply GetVersion(const IOCtlVRequest& request)
{
if (!request.HasNumberOfValidVectors(0, 1))
@ -159,6 +141,32 @@ IPCReply GetRealProductCode(const IOCtlVRequest& request)
} // namespace
IPCReply DolphinDevice::GetSystemTime(const IOCtlVRequest& request) const
{
if (!request.HasNumberOfValidVectors(0, 1))
{
return IPCReply(IPC_EINVAL);
}
if (request.io_vectors[0].size != 4)
{
return IPCReply(IPC_EINVAL);
}
// This ioctl is used by emulated software to judge if emulation is running too fast or slow.
// By using Common::Timer, the same clock Dolphin uses internally for the same task is exposed.
// Return elapsed time instead of current timestamp to make buggy emulated code less likely to
// have issuses.
const u32 milliseconds = static_cast<u32>(m_timer.ElapsedMs());
Memory::Write_U32(milliseconds, request.io_vectors[0].address);
return IPCReply(IPC_SUCCESS);
}
DolphinDevice::DolphinDevice(Kernel& ios, const std::string& device_name) : Device(ios, device_name)
{
m_timer.Start();
}
std::optional<IPCReply> DolphinDevice::IOCtlV(const IOCtlVRequest& request)
{
if (Core::WantsDeterminism())

View File

@ -3,6 +3,7 @@
#pragma once
#include "Common/Timer.h"
#include "Core/IOS/Device.h"
namespace IOS::HLE
@ -10,8 +11,12 @@ namespace IOS::HLE
class DolphinDevice final : public Device
{
public:
// Inherit the constructor from the Device class, since we don't need to do anything special.
using Device::Device;
DolphinDevice(Kernel& ios, const std::string& device_name);
std::optional<IPCReply> IOCtlV(const IOCtlVRequest& request) override;
private:
IPCReply GetSystemTime(const IOCtlVRequest& request) const;
Common::Timer m_timer;
};
} // namespace IOS::HLE

View File

@ -657,7 +657,7 @@ std::optional<IPCReply> Kernel::HandleIPCCommand(const Request& request)
return IPCReply{IPC_EINVAL, 550_tbticks};
std::optional<IPCReply> ret;
const u64 wall_time_before = Common::Timer::GetTimeUs();
const u64 wall_time_before = Common::Timer::NowUs();
switch (request.command)
{
@ -686,7 +686,7 @@ std::optional<IPCReply> Kernel::HandleIPCCommand(const Request& request)
break;
}
const u64 wall_time_after = Common::Timer::GetTimeUs();
const u64 wall_time_after = Common::Timer::NowUs();
constexpr u64 BLOCKING_IPC_COMMAND_THRESHOLD_US = 2000;
if (wall_time_after - wall_time_before > BLOCKING_IPC_COMMAND_THRESHOLD_US)
{

View File

@ -371,12 +371,12 @@ void BluetoothRealDevice::UpdateSyncButtonState(const bool is_held)
{
if (m_sync_button_state == SyncButtonState::Unpressed && is_held)
{
m_sync_button_held_timer.Update();
m_sync_button_held_timer.Start();
m_sync_button_state = SyncButtonState::Held;
}
if (m_sync_button_state == SyncButtonState::Held && is_held &&
m_sync_button_held_timer.GetTimeDifference() > SYNC_BUTTON_HOLD_MS_TO_RESET)
m_sync_button_held_timer.ElapsedMs() > SYNC_BUTTON_HOLD_MS_TO_RESET)
m_sync_button_state = SyncButtonState::LongPressed;
else if (m_sync_button_state == SyncButtonState::Held && !is_held)
m_sync_button_state = SyncButtonState::Pressed;

View File

@ -62,8 +62,8 @@ private:
// Arbitrarily chosen value that allows emulated software to send commands often enough
// so that the sync button event is triggered at least every 200ms.
// Ideally this should be equal to 0, so we don't trigger unnecessary libusb transfers.
static constexpr int TIMEOUT = 200;
static constexpr int SYNC_BUTTON_HOLD_MS_TO_RESET = 10000;
static constexpr u32 TIMEOUT = 200;
static constexpr u32 SYNC_BUTTON_HOLD_MS_TO_RESET = 10000;
std::atomic<SyncButtonState> m_sync_button_state{SyncButtonState::Unpressed};
Common::Timer m_sync_button_held_timer;

View File

@ -224,7 +224,7 @@ NetPlayClient::NetPlayClient(const std::string& address, const u16 port, NetPlay
break;
}
}
if (connect_timer.GetTimeElapsed() > 5000)
if (connect_timer.ElapsedMs() > 5000)
break;
}
m_dialog->OnConnectionError(_trans("Could not communicate with host."));

View File

@ -240,9 +240,10 @@ void NetPlayServer::ThreadFunc()
while (m_do_loop)
{
// update pings every so many seconds
if ((m_ping_timer.GetTimeElapsed() > 1000) || m_update_pings)
if ((m_ping_timer.ElapsedMs() > 1000) || m_update_pings)
{
m_ping_key = Common::Timer::GetTimeMs();
// only used as an identifier, not time value, so truncation is fine
m_ping_key = static_cast<u32>(Common::Timer::NowMs());
sf::Packet spac;
spac << MessageID::Ping;
@ -951,7 +952,8 @@ unsigned int NetPlayServer::OnData(sf::Packet& packet, Client& player)
case MessageID::Pong:
{
const u32 ping = (u32)m_ping_timer.GetTimeElapsed();
// truncation (> ~49 days elapsed) should never happen here
const u32 ping = static_cast<u32>(m_ping_timer.ElapsedMs());
u32 ping_key = 0;
packet >> ping_key;
@ -1459,7 +1461,8 @@ bool NetPlayServer::StartGame()
m_timebase_by_frame.clear();
m_desync_detected = false;
std::lock_guard lkg(m_crit.game);
m_current_game = Common::Timer::GetTimeMs();
// only used as an identifier, not time value, so truncation is fine
m_current_game = static_cast<u32>(Common::Timer::NowMs());
// no change, just update with clients
if (!m_host_input_authority)

View File

@ -270,6 +270,42 @@ static int GetEmptySlot(std::map<double, int> m)
return -1;
}
// Arbitrarily chosen value (38 years) that is subtracted in GetSystemTimeAsDouble()
// to increase sub-second precision of the resulting double timestamp
static constexpr int DOUBLE_TIME_OFFSET = (38 * 365 * 24 * 60 * 60);
static double GetSystemTimeAsDouble()
{
// FYI: std::chrono::system_clock epoch is not required to be 1970 until c++20.
// We will however assume time_t IS unix time.
using Clock = std::chrono::system_clock;
// TODO: Use this on switch to c++20:
// const auto since_epoch = Clock::now().time_since_epoch();
const auto unix_epoch = Clock::from_time_t({});
const auto since_epoch = Clock::now() - unix_epoch;
const auto since_double_time_epoch = since_epoch - std::chrono::seconds(DOUBLE_TIME_OFFSET);
return std::chrono::duration_cast<std::chrono::duration<double>>(since_double_time_epoch).count();
}
static std::string SystemTimeAsDoubleToString(double time)
{
// revert adjustments from GetSystemTimeAsDouble() to get a normal Unix timestamp again
time_t seconds = (time_t)time + DOUBLE_TIME_OFFSET;
tm* localTime = localtime(&seconds);
#ifdef _WIN32
wchar_t tmp[32] = {};
wcsftime(tmp, std::size(tmp), L"%x %X", localTime);
return WStringToUTF8(tmp);
#else
char tmp[32] = {};
strftime(tmp, sizeof(tmp), "%x %X", localTime);
return tmp;
#endif
}
static std::string MakeStateFilename(int number);
// read state timestamps
@ -284,7 +320,7 @@ static std::map<double, int> GetSavedStates()
{
if (ReadHeader(filename, header))
{
double d = Common::Timer::GetDoubleTime() - header.time;
double d = GetSystemTimeAsDouble() - header.time;
// increase time until unique value is obtained
while (m.find(d) != m.end())
@ -359,7 +395,7 @@ static void CompressAndDumpState(CompressAndDumpState_args save_args)
StateHeader header{};
SConfig::GetInstance().GetGameID().copy(header.gameID, std::size(header.gameID));
header.size = s_use_compression ? (u32)buffer_size : 0;
header.time = Common::Timer::GetDoubleTime();
header.time = GetSystemTimeAsDouble();
f.WriteArray(&header, 1);
@ -471,7 +507,7 @@ std::string GetInfoStringOfSlot(int slot, bool translate)
if (!ReadHeader(filename, header))
return translate ? Common::GetStringT("Unknown") : "Unknown";
return Common::Timer::GetDateTimeFormatted(header.time);
return SystemTimeAsDoubleToString(header.time);
}
u64 GetUnixTimeOfSlot(int slot)
@ -481,8 +517,7 @@ u64 GetUnixTimeOfSlot(int slot)
return 0;
constexpr u64 MS_PER_SEC = 1000;
return static_cast<u64>(header.time * MS_PER_SEC) +
(Common::Timer::DOUBLE_TIME_OFFSET * MS_PER_SEC);
return static_cast<u64>(header.time * MS_PER_SEC) + (DOUBLE_TIME_OFFSET * MS_PER_SEC);
}
static void LoadFileStateData(const std::string& filename, std::vector<u8>& ret_data)