ミリ秒単位で現在時刻を取得する関数
BREW にはいくつかの時間を取得するための関数があります。
- GETTIMESECONDS() は 1980年1月6日00:00:00 からの秒数を返します。
- GETTIMEMS() は 00:00:00 からの時間を取得します。
この2つの関数を組み合わせれば、1980年1月6日00:00:00からの経過時間をミリ秒単位で時間を取得することができます。
uint64 current_time_millis() { uint32 seconds = GETTIMESECONDS(); uint32 days = seconds / (24 * 60 * 60); // 日単位に変換 uint64 millis = (uint64)days * (24 * 60 * 60 * 1000); // ミリ秒単位に変換(時分秒の情報は消えている) return millis + GETTIMEMS(); // 00:00:00 からの時間を足して現在時刻に設定 }
無駄な部分を消して、
uint64 current_time_millis() { return GETTIMESECONDS() / 86400 * 86400000ULL + GETTIMEMS(); }
と書くのもありです。
Java の System.currentTimeMillis() に相当する関数がほしい場合はこれを使うと幸せになれるかも。こっちは 1970年1月1日00:00:00 からの時間ですが。
おまけ
C++0x の chrono で書くとこんな感じになるはず?
// epoch は 1980年1月6日00:00:00 struct brew_system_clock { typedef std::chrono::seconds duration; typedef duration::rep rep; typedef duration::period period; typedef std::chrono::time_point<brew_system_clock, duration> time_point; static const bool is_monotonic = false; // epoch からの秒数 static time_point now() { return time_point(duration(GETTIMESECONDS())); } }; // epoch は 1980年1月6日00:00:00 struct brew_high_resolution_clock { typedef std::chrono::milliseconds duration; typedef duration::rep rep; typedef duration::period period; typedef std::chrono::time_point<brew_system_clock, duration> time_point; static const bool is_monotonic = false; // epoch からのミリ秒数 static time_point now() { typedef std::chrono::duration<std::int32_t, ratio<24 * 60 * 60> > day; return std::chrono::time_point_cast<day>(brew_system_clock::now()) + duration(GETTIMEMS()); } };