在C STD中,如何在运行时选择计时持续时间
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
类中使用它,该类可测量某些功能的代码执行持续时间。我要做的是创建一个switch
,通过该CAM定义结果是否应将结果存储为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::chrono::system_clock::time_point
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 时间持续时间到时间字符串
- 指向(数据)成员的指针作为非类型模板参数,例如具有自动存储持续时间/无链接
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 将毫秒转换为给定格式的持续时间
- 具有静态存储持续时间的常量初始化变量的初始化顺序
- 划分和乘以STD :: Chrono ::持续时间
- 静态存储持续时间初始化
- C++计划持续时间内(字体)资源的分配
- FFMPEG:具有不同持续时间的多路复用流
- 在不同翻译单元中具有静态存储持续时间的依赖非局部常量浮点变量的常量初始化
- 使用System_Clock :: TO_TIME_T警告持续时间_t
- 访问和存储/解析性std :: Chrono ::持续时间:: milliseconds(cpprest)时使用什么类型
- 我可以让QT到概要文件插槽执行持续时间吗?
- 在STD :: Chrono ::剩余时间测量的持续时间
- 自定义 AVIOContext 的未定义 AVFormatContext 持续时间
- 使用计时比较C++的持续时间/秒数并不像预期的那样工作
- 为什么 std::future::wait_for 不等待正确的持续时间
- 在C STD中,如何在运行时选择计时持续时间