Brianna Szvenska Brianna Szvenska -4 years ago 131
C++ Question

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

I have been searching for this but didn't find a solution to the exact problem.

In short, is there a way to computationally define the duration of a std::chronos variable? Take for instance the following piece of code:

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


I use that in a custom
Timer
class that measures the duration of code execution for some functions. What I am trying to do is to create a
switch
through which one cam define whether the results should be stored as
microseconds
,
milliseconds
or
seconds
.

What would be the way to achieve that in C++?

Answer Source

You could do something similar to this (assume sc is std::chrono). As you can see the cast is a template parameter (a compile-time parameter):

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();
  }
};

Usage:

Timer t;
...
t.elapsed<sc::milliseconds>();

Now if you want a simple switch of units at run-time, just wrap your template function into a function that instantiates your Timer::getElapsed function with the appropiate cast and you are done at least for simple cases:

enum class UnitCount { ms, s };

int Timer::getElapsedInUnits(UnitCount c) {
    switch (c) {
      case UnitCount::ms:
         return this->getElapsed<sc::milliseconds>();
      case UnitCount::s
         ...
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download