gpt4 book ai didi

c++ - 不同计算机上的时钟时序变化

转载 作者:行者123 更新时间:2023-12-03 06:53:36 25 4
gpt4 key购买 nike

我正在我的 github 上为 DMG-01(A.K.A gameboy 1989)开发一个实现。我已经实现了 APU 和 PPU,在我的电脑(和我 friend 的电脑)上(几乎)完美的计时。但是,当我在我 friend 的一台电脑上运行模拟器时,它的运行速度是我或其他 friend 的两倍

同步时钟(在 gameboy 和运行它的 pc 之间)的代码如下:

Clock.h 头文件:

class Clock
{
// ...
public:
void SyncClock();

private:
/* API::LR35902_HZ_CLOCK is 4'194'304 */
using lr35902_clock_period = std::chrono::duration<int64_t, std::ratio<1, API::LR35902_HZ_CLOCK>>;
static constexpr lr35902_clock_period one_clock_period{1};
using clock = std::chrono::high_resolution_clock;

private:
decltype(clock::now()) _last_tick{std::chrono::time_point_cast<clock::duration>(clock::now() + one_clock_period)};
};

时钟.cpp文件

void Clock::SyncClock()
{
// Sleep until one tick has passed.
std::this_thread::sleep_until(this->_last_tick);

// Use time_point_cast to convert (via truncation towards zero) back to
// the "native" duration of high_resolution_clock
this->_last_tick = std::chrono::time_point_cast<clock::duration>(this->_last_tick + one_clock_period);
}

在 main.cpp 中这样调用:

int main()
{
// ...
while (true)
{
// processor.Clock() returns the number of clocks it took for the processor to run the
// current instruction. We need to sleep this thread for each clock passed.
for (std::size_t current_clock = processor.Clock(); current_clock > 0; --current_clock)
{
clock.SyncClock();
}
}
// ...
}

为什么在这种情况下 chrono 在其他计算机上会以不同的方式受到影响?时间是绝对的,我会理解为什么在一台电脑上运行模拟器会,但为什么更快?我检查了我的时钟类型 (high_resolution_clock),但我不明白为什么会这样。谢谢!

最佳答案

我认为您可能遇到了 <chrono> 的溢出问题.

表达式:

clock::now() + one_clock_period

有问题。 clockhigh_resolution_clock , 这很常见 nanoseconds解析度。 one_clock_period单位为 1/4'194'304 .结果表达式将是 time_pointperiod1/8'192'000'000'000 .

使用带符号的 64 位整数类型,max()这样的精度略高于 13 天。所以如果clock::now()返回 .time_since_epoch()大于 13 天,_last_tick将溢出,有时可能为负(取决于 clock::now() 超过 13 天的数量)。

要正确尝试类型转换 one_clock_period精确到 clock立即:

static constexpr clock::duration one_clock_period{
std::chrono::duration_cast<clock::duration>(lr35902_clock_period{1})};

关于c++ - 不同计算机上的时钟时序变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64352614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com