我有以下 Timer 类来简化获取自一个纪元以来经过的时间:
#include <chrono>
class Timer {
public:
void start(void);
template <typename duration_type>
const duration_type time_elapsed(void);
private:
std::chrono::high_resolution_clock::time_point epoch;
};
void Timer::start(void) {
epoch = std::chrono::high_resolution_clock::now();
}
template <typename duration_type>
const duration_type Timer::time_elapsed(void) {
return std::chrono::duration_cast<duration_type>(std::chrono::high_resolution_clock::now() - epoch);
}
int main(void) {
Timer timer;
timer.start();
// pointless loop to cause a delay
for (int x = 1; x < 1000000; ++x) {
x * x * x;
}
std::chrono::nanoseconds elapsed = timer.time_elapsed<std::chrono::nanoseconds>();
std::cout << elapsed.count() << std::endl;
return 0;
}
我有一种感觉,通过使 Timer::time_elapsed() 成为模板函数,我的课程过于复杂,并且理想情况下希望将其用法简化为以下内容:
std::chrono::nanoseconds elapsed = timer.time_elapsed();
std::cout << elapsed.count() << std::endl;