检测代码运行效率 GetTickCount()的使用

调试程序的时很多时候都想知道自己写的程序运行的效率,也就是说因该得到这段程序运行的时间,我下面介绍这个函数就可以完成这个功能,她就是:GetTickCount()

    下面是MSDN上的解释:
   GetTickCount
     The GetTickCount function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the system timer. To obtain the system timer resolution, use the GetSystemTimeAdjustment function.
DWORD GetTickCount(VOID);
Parameters
This function has no parameters.
Return Values

The return value is the number of milliseconds that have elapsed since the system was started.

Remarks

The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days.

If you need a higher resolution timer, use a multimedia timer or a high-resolution timer.

Windows NT/2000/XP: To obtain the time elapsed since the computer was started, retrieve the System Up Time counter in the performance data in the registry key HKEY_PERFORMANCE_DATA. The value returned is an 8-byte value. For more information, see Performance Monitoring.

Example Code

The following example demonstrates how to handle timer wrap around.

DWORD dwStart = GetTickCount();

// Stop if this has taken too long
if( GetTickCount() - dwStart >= TIMELIMIT )
    Cancel();
这个函数是取得程序运行到现在的时间,这样在检测代码的前后各运行一次这个函数,两次的差就是程序运行的大概的时间了。例如:
DWORD dwStart;
DWORD dwEnd;
dwStart = GetTickCount();
//要检测的代码
dwEnd = GetTickCount();
CString s ;
s.Format( "%d", dwEnd- dwStart ) ;
AfxMessageBox( s ) ;
这个函数也可以用作定时,例如:

#i nclude <windows.h>

#i nclude <stdio.h>

void main()

{

   DWORD dwLast;

    DWORD dwCurrent;

     DWORD dwInterval = 1000;

dwLast = GetTickCount();

     int i = 0;

     while(true)

     {

         dwCurrent = GetTickCount();

         if( dwCurrent - dwLast < dwInterval )

              continue;

        //your code to be executed when interval is elapsed

         printf("dwLast,dwCurrent,diff:%d,%d,%d/n",dwLast,dwCurrent,dwCurrent-dwLast);

        //your code to determine when to break

         if( i > 10 ) break;

         i++;

         dwLast = dwCurrent;

     }

   getchar();  

   return

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值