zoukankan      html  css  js  c++  java
  • 如何测试代码执行耗时?

    #include <chrono>
    #include <ctime>
    class Timer
    {
    public:
    	Timer() :running_(false),
    		has_run_at_least_once_(false)
    	{
    
    	}
    	virtual ~Timer()
    	{
    
    	}
    	virtual void Start()
    	{
    		if (!running())
    		{
    			start_cpu_ = std::chrono::high_resolution_clock::now();
    			running_ = true;
    			has_run_at_least_once_ = true;
    		}
    	}
    	virtual void Stop()
    	{
    		if (running())
    		{
    			stop_cpu_ = std::chrono::high_resolution_clock::now();
    			running_ = false;
    		}
    	}
    	virtual float Nanoseconds()
    	{
    		if (!has_run_at_least_once())
    		{
    			printf("Timer has never been run before reading time.");
    			return 0;
    		}
    		return std::chrono::duration_cast<std::chrono::nanoseconds>(stop_cpu_ - start_cpu_).count();
    	}
    	virtual float MilliSeconds()
    	{
    		if (!has_run_at_least_once())
    		{
    			printf("Timer has never been run before reading time.");
    			return 0;
    		}
    		return std::chrono::duration_cast<std::chrono::milliseconds>(stop_cpu_ - start_cpu_).count();
    	}
    	virtual float MicroSeconds()
    	{
    		if (!has_run_at_least_once())
    		{
    			printf("Timer has never been run before reading time.");
    			return 0;
    		}
    		return std::chrono::duration_cast<std::chrono::microseconds>(stop_cpu_ - start_cpu_).count();
    	}
    	virtual float Seconds()
    	{
    		return MilliSeconds() / 1000.0;
    	}
    	inline bool running() { return running_; }
    	inline bool has_run_at_least_once() { return has_run_at_least_once_; }
    private:
    	bool running_;
    	bool has_run_at_least_once_;
    	std::chrono::high_resolution_clock::time_point start_cpu_;
    	std::chrono::high_resolution_clock::time_point stop_cpu_;
    };
    
  • 相关阅读:
    poj 2195 Going Home
    poj 3068 "Shortest" pair of paths
    aoj 2226 Merry Christmas
    poj 2226 Muddy Fields
    foj Problem 2275 Game
    foj Problem 2283 Tic-Tac-Toe
    XidianOJ 1081 锘爷与矩阵
    XidianOJ 1061 a+boflw
    XidianOJ 1080 锘爷与跳楼塔
    XidianOJ 1017 Codeforce上的rating
  • 原文地址:https://www.cnblogs.com/cheungxiongwei/p/9087675.html
Copyright © 2011-2022 走看看