如果我理解您的问题,并且如果您在编译时知道所有不同的时间分辨率,那么以下内容将满足您的需求。您可以通过使用所有不同的时间分辨率来计算正确的刻度周期,common_type
如下所示:
#include <cstdint>
#include <chrono>
struct clock
{
typedef std::uint64_t rep;
typedef std::common_type
<
std::chrono::duration<rep, std::ratio<1, 50>>,
std::chrono::duration<rep, std::ratio<1, 30>>,
std::chrono::duration<rep, std::ratio<1001, 30000>>
>::type duration;
typedef duration::period period;
typedef std::chrono::time_point<clock> time_point;
static const bool is_steady = true;
static time_point now()
{
// just as an example
using namespace std::chrono;
return time_point(duration_cast<duration>(steady_clock::now().time_since_epoch()));
}
};
这将在编译时计算最大的刻度周期,它将准确地代表您指定的每个分辨率。例如,用这个时钟可以准确地表示:
- 1/50 有 600 个刻度。
- 1/30 有 1000 个刻度。
- 1001/30000 有 1001 个刻度。
下面的代码对此进行了练习,并使用此处clock
描述的“chrono_io”工具不仅打印出时钟滴答的运行时数量,还打印出时钟滴答的编译时间单位:
#include <iostream>
#include <thread>
#include "chrono_io"
int main()
{
auto t0 = clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
auto t1 = clock::now();
std::cout << (t1-t0) << '\n';
}
对我来说,这打印出来:
633 [1/30000]seconds
含义:调用之间有 633 个时钟滴答now()
,每个滴答的单位是 1/30000 秒。如果您不想受制于“chrono_io”,您可以使用clock::period::num
和检查时钟的单位clock::period::den
。
如果您的不同时间分辨率不是编译时信息,那么您当前的解决方案boost::rational
可能是最好的。