Skip to content

Instantly share code, notes, and snippets.

@ksasao
Last active September 18, 2021 07:06
Show Gist options
  • Select an option

  • Save ksasao/159727cb3c0909ba2adfc7c269401ac2 to your computer and use it in GitHub Desktop.

Select an option

Save ksasao/159727cb3c0909ba2adfc7c269401ac2 to your computer and use it in GitHub Desktop.
RTC時刻(秒)とシステム時刻(ミリ秒)からミリ秒単位のRTC補正時刻を求めるアルゴリズム。offset はより広いスコープで定義しておく。https://twitter.com/ksasao/status/1439058457856937985
// RTC時刻(秒)とシステム時刻(ミリ秒)を読み込み
long rtcSec = GetRtcSec();
long systemMillsec = GetSystemMillisec();
// delta ができるだけ 0~999 に収まるようにする
long delta = (systemMillsec + offset) - rtcSec * 1000;
// 100ms 以上のずれがある場合は offset を再計算
int d = 100;
if(delta > 1000 + d || delta < -d)
{
offset = rtcSec * 1000 - systemMillsec;
}
// それほどずれていない場合は少しだけ補正する
if (delta >= 1000)
{
offset = offset - 1;
}
else if(delta < 0)
{
offset = offset + 1;
}
// 秒単位のRTCの時刻をシステムのミリ秒で補正した値
long estimatedRtcMillisec = systemMillsec + offset;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment