我正在我的github上实现DMG-01(即GameBoy 1989年版),涉及IT技术相关内容。 我已经在我的电脑以及朋友的电脑上实现了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)};
};
Clock.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),但我不知道为什么会出现这种情况。 谢谢!
std::high_resolution_clock
的period
类型,这两个系统之间是否有区别? - Some programmer dudestd::ratio
的num
和den
成员的日志记录即可。 - Some programmer dude