方法一、
#include<iosteam>
#include<ctime>
using namespace std;
class CTimer
{
public:
CTimer()
{
_start=clock();
}
~CTimer()
{
_end=clock();
cout<< float(_end - _start) / CLK_TCK <<endl;
}
private:
clock_t _start;
clock_t _end;
};
void main()
{
CTimer t;
//程序执行部分!
}
方法二:
//在windows下实现(毫秒级):
DWORD dwStart = GetTickCount(); //取windows启动到现在的流逝时间(毫秒)
Run_Your_Func(...); //运行你的函数
DWORD dwUsed = GetTickCount() - dwStart; //计算该函数所消耗的时间
方法三:
这比微秒还准!依赖于你的处理器!!!
class CTimer
{
public:
CTimer()
{
QueryPerformanceFrequency(&m_Frequency);
Start();
}
void Start()
{
QueryPerformanceCounter(&m_StartCount);
}
double End()
{
LARGE_INTEGER CurrentCount;
QueryPerformanceCounter(&CurrentCount);
return double(CurrentCount.LowPart - m_StartCount.LowPart) / (double)m_Frequency.LowPart;
}
void ShowNow()
{
LARGE_INTEGER CurrentCount;
QueryPerformanceCounter(&CurrentCount);
cout<<"Timer Count is:"<<double(CurrentCount.LowPart - m_StartCount.LowPart) / (double)m_Frequency.LowPart<<endl;
}
private:
LARGE_INTEGER m_Frequency;
LARGE_INTEGER m_StartCount;
};
下面是你的程序,比如:
int a;
for ( int i = 0; i < 10000;, i++ )
a++;
你想测它的时间的话这样写:
CTimer t;
int a;
for ( int i = 0; i < 10000;, i++ )
a++;
cout<<"用时"<<t.end()<<"秒"<<endl;
方法四:
我写过一个宏,专门干这个的!
#include "window.h"
#define BEGIN_RECORD\
{\
long ____temp_begin_time___;\
____temp_begin_time___=::GetTickCount();
#define END_RECORD(dtime)\
dtime=::GetTickCount()-____temp_begin_time___;\
}
用法:
long tim;
BEGIN_RECORD
被测函数;
END_RECORD(tim);//tim就是所求的时间差!