简单计时器类 计算时间间隔

// 简单记时器,linux精确到微秒,windows到毫秒,获取的时间间隔单位为秒
#ifdef _WIN32
	class EasyTimer
	{
	public:
		EasyTimer(bool startNow = false)
		{
			if (startNow)
				_start = GetTickCount();
		}
		~EasyTimer(){}
	public:
		double elapsed()
		{
			return (double)(GetTickCount() - _start)/1000;
		}
		void restart()
		{
			_start = GetTickCount();
		}
	private:
		uint64_t _start;
	};
#else
	class EasyTimer
	{
	public:
		EasyTimer(bool startNow = false)
		{
			if (startNow)
				gettimeofday(&_tv, NULL);
		}
		~EasyTimer(){}
	public:
		double elapsed()
		{
			struct timeval now;
			gettimeofday(&now, NULL);
			return (double)((now.tv_sec - _tv.tv_sec)*1000000 + (now.tv_usec - _tv.tv_usec))/1000000;
		}
		void restart()
		{
			gettimeofday(&_tv, NULL);
		}
	private:
		struct timeval _tv;
	};
#endif

你可能感兴趣的:(简单计时器类 计算时间间隔)