法一利用GetTickCount函数
获取程序运行时间
。。。 long t1=GetTickCount();//程序段开始前取得系统运行时间(ms) 。。。。。。//to do sth long t2=GetTickCount();//程序段结束后取得系统运行时间(ms) cout<<t2-t1<<endl;//前后之差即程序运行时间 。。。
法二利用C/C++计时函数
获取程序运行时间
代码
#include "time.h"
。。。
clock_t start, finish;
start = clock();
。。。。。。//to do sth
finish = clock();
//cout<<(double)(finish-start)/CLOCKS_PER_SEC<<" seconds"<<endl;
printf("%f seconds\n",(double)(finish-start)/CLOCKS_PER_SEC);
。。。
函数/参数说明
clock() | C/C++计时函数,与其相关的数据类型是clock_t 返回:从"此程序进程开启"到"程序中调用clock()函数"之间CPU计时单元数,MSDN中称挂钟时间(wal-clock) |
clock_t | 用来保存时间的数据类型,在time.h中定义:typedef long clock_t; 为长整型 |
CLOCKS_PER_SEC | 用来表示一秒钟会有多少个时钟计时单元,在time.h中定义:#define CLOCKS_PER_SEC ((clock_t)1000) |
获取系统运行的时间
法三 利用CTime类获取系统时间
CString str; //获取系统时间 CTime tm; tm=CTime::GetCurrentTime(); str=tm.Format("现在时间是%Y年%m月%d日 %X"); AfxMessageBox(str);
法四 利用GetLocalTime类获取系统时间
代码
SYSTEMTIME st;
CString strDate,strTime;
GetLocalTime(&st);
strDate.Format("%4d-%2d-%2d",st.wYear,st.wMonth,st.wDay);
strTime.Format("%2d:%2d:%2d",st.wHour,st.wMinute,st.wSecond);
AfxMessageBox(strDate);
AfxMessageBox(strTime);
方法 四、QueryPerformanceFrequency()和QueryPerformanceCounter()函数
误差不超过1微秒,精度与CPU等机器配置有关。
------------------------------------------------------------------------------------
LARGE_INTEGER litmp;
LONGLONG QPart1,Qpart2;
double dfMinus,dfFreq,dfTime;
//获得计时器的时钟频率
QueryPerformanceFrequency(&litmp);
dfFreq = (double)litmp.QuadPart;
//开始计时
QueryPerformanceCounter(&litmp);
Qpart1 = litmp.QuadPart;
......; //函数等,根据需要添加。
//终止计时
QueryPerformanceCounter(&litmp);
Qpart2 = litmp.QuadPart;
//计算时间
dfMinus = (double)(QPart2 - QPart1); //计数器值
dfTime = dfMinus / dfFreq; //对应时间,单位为秒,可以乘1000000精确到微秒级(us)
封装到函数中
BOOL MySleep(DWORD dwInterval)
///
// 功能:执行微秒级的延时功能
// 参数:Interval 参数为需要的延时数(单位:微秒)
// 返回值:若计算机硬件不支持此功能,返回FALSE,若函数执行成功,返回TRUE
///
{
BOOL bNormal = TRUE;
LARGE_INTEGER frequence, privious, current, interval;
if(!QueryPerformanceFrequency( &frequence))
{
::MessageBox(NULL, "Your computer hardware doesn't support the high-resolution performance counter",
"Not Support", MB_ICONEXCLAMATION | MB_OK); //或其它的提示信息
return FALSE;
}
interval.QuadPart = frequence.QuadPart * dwInterval / 1000000;
bNormal = bNormal && QueryPerformanceCounter( &privious );
current = privious;
while( current.QuadPart - privious.QuadPart < interval.QuadPart )
bNormal = bNormal && QueryPerformanceCounter( ¤t );
return bNormal;
}
机器在执行此函数中的代码也需要时间,所以在需要几个微秒的延时,会影响精度。
1、WM_TIMER消息映射
SetTimer()设置定时间隔,定时响应函数 OnTimer()
计时精度30ms,定时器消息在多任务操作系统中的优先级很低,不能得到及时响应。
2、sleep()函数
计时精度30ms,CPU占用率高,延时期间不能处理其他的消息。