在 C++ std 中,如何在 运行 时间内选择 chronos 的持续时间
In C++ std, how to choose the duration of chronos during run-time
我一直在寻找这个,但没有找到确切问题的解决方案。
简而言之,有没有一种方法可以计算定义 std::chronos 变量的持续时间?以下面的一段代码为例:
auto timed = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();
我在自定义 Timer
class 中使用它来测量某些函数的代码执行持续时间。我想做的是创建一个 switch
,一个凸轮通过它定义结果是否应存储为 microseconds
、milliseconds
或 seconds
.
在 C++ 中实现它的方法是什么?
你可以做类似的事情(假设 sc
是 std::chrono
)。如您所见,强制转换是模板参数(编译时参数):
class Timer {
sc::time_point<sc::steady_clock> _start;
Timer() : _start(sc::steady_clock::now()) {
}
template <class Unit>
int getElapsed() {
return sc::duration_cast<Unit>(sc::steady_clock::now() - _start).count();
}
};
用法:
Timer t;
...
t.elapsed<sc::milliseconds>();
现在,如果您想要在 运行 时间进行简单的单位切换,只需将您的模板函数包装到一个函数中,该函数使用适当的转换实例化您的 Timer::getElapsed
函数,您至少完成了对于简单的情况:
enum class UnitCount { ms, s };
int Timer::getElapsedInUnits(UnitCount c) {
switch (c) {
case UnitCount::ms:
return this->getElapsed<sc::milliseconds>();
case UnitCount::s
...
}
}
我一直在寻找这个,但没有找到确切问题的解决方案。
简而言之,有没有一种方法可以计算定义 std::chronos 变量的持续时间?以下面的一段代码为例:
auto timed = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();
我在自定义 Timer
class 中使用它来测量某些函数的代码执行持续时间。我想做的是创建一个 switch
,一个凸轮通过它定义结果是否应存储为 microseconds
、milliseconds
或 seconds
.
在 C++ 中实现它的方法是什么?
你可以做类似的事情(假设 sc
是 std::chrono
)。如您所见,强制转换是模板参数(编译时参数):
class Timer {
sc::time_point<sc::steady_clock> _start;
Timer() : _start(sc::steady_clock::now()) {
}
template <class Unit>
int getElapsed() {
return sc::duration_cast<Unit>(sc::steady_clock::now() - _start).count();
}
};
用法:
Timer t;
...
t.elapsed<sc::milliseconds>();
现在,如果您想要在 运行 时间进行简单的单位切换,只需将您的模板函数包装到一个函数中,该函数使用适当的转换实例化您的 Timer::getElapsed
函数,您至少完成了对于简单的情况:
enum class UnitCount { ms, s };
int Timer::getElapsedInUnits(UnitCount c) {
switch (c) {
case UnitCount::ms:
return this->getElapsed<sc::milliseconds>();
case UnitCount::s
...
}
}