3

我正在我的 github 上实现 DMG-01(AKA gameboy 1989)。我已经实现了 APU 和 PPU,在我的电脑(和我朋友的电脑)上具有(几乎)完美的时机。然而,当我在我朋友的一台电脑上运行模拟器时,它的运行速度是我或其他朋友的两倍。

同步时钟的代码(在游戏机和运行它的电脑之间)如下:

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),但我不明白为什么会这样。谢谢!

4

1 回答 1

4

我认为您可能在<chrono>.

表达方式:

clock::now() + one_clock_period

是有问题的。 clockhigh_resolution_clock,并且这通常具有nanoseconds分辨率。 one_clock_period有单位1/4'194'304。结果表达式将是 a time_pointwith a periodof 1/8'192'000'000'000

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

要更正尝试强制转换one_clock_periodclock立即的精度:

static constexpr clock::duration one_clock_period{
    std::chrono::duration_cast<clock::duration>(lr35902_clock_period{1})};
于 2020-10-14T13:07:45.023 回答