大家好,又见面了,我是全栈君
#pragma once
#include <ctime>
#include <limits>
class timer
{
public:
timer(){ _start_time = clock(); }
void restart(){ _start_time = clock(); }
double elapsed() const
{
return (double)(clock() - _start_time) / CLOCKS_PER_SEC;
}
double elapsed_min() const
{
return (double)(1) / (double)CLOCKS_PER_SEC;
}
double elapsed_max() const
{
return (double)(std::numeric_limits<clock_t>::max() - _start_time) / double(CLOCKS_PER_SEC);
}
private:
clock_t _start_time;
};timer的计数使用了标准头文件<ctime>里的clock()函数,它返回自进程启动以来的clock计数,每秒的clock数由宏CLOCKS_PER_SEC定义,CLOCKS_PER_SEC的值因操作系统而不同,在win32下是1000,而在linux下则是1000000,页就是说在win32下的精度是毫秒,在linux下的精度是微妙。
说白了,它是一个模板类,它主要是把C++当中的一些内建型别进行了封装,比如说numeric_limits<int>是一个特化后的类,从这个类的成员变量与成员函数中,我们可以了解到int的很多特性:可以表示的最大值,最小值,是否是精确的,是否是有符号等等。如果用其他任意(非内建类型)来特化这个模板类,比如string,string怎么可能有最大值?我们从MSDN上可以了解到,这对string,成员变量与成员函数是没有意义的,要么返回0要么为false。
参考博客:http://blog.163.com/wujiaxing009%40126/blog/static/7198839920124135147911/
timer不适合高精度的时间测量任务,它的精度依赖操作系统或编译器,难以做到跨平台,timer也不适合大跨度时间段的测量,可提供的最大时间跨度只有几百个小时,如果需要以天、月甚至年作为时间的单位则不能使用timer,应使用date_time.
template<int N = 2>
class new_progress_timer : public timer
{
public:
new_progress_timer(ostream &os = cout)
:m_os(os)
{
}
~new_progress_timer()
{
try
{
// 保存流的状态
ostream::fmtflags old_flags = m_os.setf(ostream::fixed, ostream::floatfield);
streamsize old_prec = m_os.precision(N);
// 输出时间
m_os << elapsed() << "s\n" << endl;
// 恢复流状态
m_os.flags(old_flags);
m_os.precision(old_prec);
}
catch (...){}
}
private:
ostream &m_os; // 需要特别注意
};继承于timer类,主要实现输出时间的精度控制
注意代码的最后一行,原因是:
protected:
__CLR_OR_THIS_CALL basic_ostream(_Myt&& _Right)
{ // construct by moving _Right
_Myios::init();
_Myios::move(_STD move(_Right));
}
_Myt& __CLR_OR_THIS_CALL operator=(_Myt&& _Right)
{ // move from _Right
this->swap(_Right);
return (*this);
}
void __CLR_OR_THIS_CALL swap(_Myt& _Right)
{ // swap with _Right
if (this != &_Right)
_Myios::swap(_Right);
}
public:
__CLR_OR_THIS_CALL basic_ostream(const _Myt&) = delete;
_Myt& __CLR_OR_THIS_CALL operator=(const _Myt&) = delete;发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/120120.html原文链接:https://javaforall.cn