时长的工具类"/>
C++中计算函数运行时长的工具类
问题
统计一个函数或代码段的耗时。
解决方案
第一版
#ifndef FUNCTION_TIMER_H
#define FUNCTION_TIMER_H#include <chrono>
#include <iostream>/*计算一个函数耗时的工具类
*/
class FunctionTimer {
public:template<typename FUNC>FunctionTimer(const FUNC& func): startTimePoint(Clock::now()) {func();}~FunctionTimer() {endTimePoint = Clock::now();auto timeSpan = std::chrono::duration_cast<std::chrono::duration<double>>(endTimePoint - startTimePoint);std::cout << "total cast: " << timeSpan.count() << " seconds" << std::endl;}FunctionTimer(const FunctionTimer&) = delete;FunctionTimer& operator=(const FunctionTimer&) = delete;private:using Clock = std::chrono::steady_clock;Clock::time_point startTimePoint;Clock::time_point endTimePoint;
};#endif
更多推荐
C++中计算函数运行时长的工具类
发布评论