vc 计算程序时间

法一利用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( &current );  
return bNormal;  
}  
机器在执行此函数中的代码也需要时间,所以在需要几个微秒的延时,会影响精度。

1、WM_TIMER消息映射
SetTimer()设置定时间隔,定时响应函数  OnTimer()

计时精度30ms,定时器消息在多任务操作系统中的优先级很低,不能得到及时响应。

2、sleep()函数
计时精度30ms,CPU占用率高,延时期间不能处理其他的消息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值