在C STD中,如何在运行时选择计时持续时间

In C++ std, how to choose the duration of chronos during run-time

本文关键字:选择 持续时间 运行时 STD      更新时间:2023-10-16

我一直在搜索此问题,但找不到解决确切问题的解决方案。

简而言之,是否有一种方法可以在计算上定义std :: Chronos变量的持续时间?以以下代码为例:

auto timed = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();

我在自定义Timer类中使用它,该类可测量某些功能的代码执行持续时间。我要做的是创建一个switch,通过该CAM定义结果是否应将结果存储为microsecondsmillisecondsseconds

在C 中实现这一目标的方法是什么?

您可以做类似的事情(假设scstd::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
         ...
    }
}