GetTickCount返回(retrieve)从操作系统启动到现在所经过(elapsed)的毫秒数,它的返回值是DWORD。GetTickCount函数的原型为:
DWORD GetTickCount(void);
它在winbase.h头文件中定义为:
WINBASEAPI DWORD WINAPI GetTickCount(VOID);
winbase.h已被包含进windows.h头文件中,所以要使用GetTickCount只需包含windows.h就可以了。
用一个DWORD类型的值存放一个时间数值,那么经历足够长的时间,这个数值一定会溢出绕回到零(wrap around to zero),我们可以计算这个时间。先算一下一天有多少毫秒mmsEachDay = 24*60*60*1000=86,400,000ms。而一个DWORD最大能表示多达数值呢?DWORD在头文件windef.h中定义如下:
typedef unsigned long DWORD;
可以看出DWORD是一个占四个字节即两个字的空间无符号整数,它能表示的最大值为2^32=4,294,967,695,而4,294,967,695/86,400,000 = 49.71,所以若系统持续运行(run continuously)49.71天,这个数会溢出绕回到零。
可以使用GetTickCount()来大概确定一段代码执行了多少时间,例程如下:
#include <Windows.h>
#include <stdio.h>
//1.计算代码运行的时间
void main()
{
DWORD dwStart;
DWORD dwEnd;
dwStart = GetTickCount();
printf("dwStart:%d\n",dwStart);
for (int i = 0;i<10000000;i++)
{
}
dwEnd = GetTickCount();
printf("dwEnd:%d\n",dwEnd);
printf("elapsed:%d\n",dwEnd - dwStart);
system("pause");
}
也可以用GetTickCount函数来进行定时,比如若要定时1s,可以使用如下代码:
//2.定时
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;
}
system("pause");
}
GetTickCount的分辨率是1ms。在精度要求不高的情况下也可以使用Sleep()函数定时,它的最小分辨率大概是55ms,Sleep的函数原型为:
void Sleep( DWORD dwMilliseconds );
Sleep在winbase.h中的定义如下:
WINBASEAPI VOID WINAPI Sleep( IN DWORD dwMilliseconds );
其中VOID是基本数据类型void的别名,可以参见winnt.h中的定义:
#ifndef VOID
#define VOID void
typedef char CHAR;
typedef short SHORT;
typedef long LONG;
#endif
如果要使用更高分辨率的话请使用多媒体定时器(multimedia timer)或高分辨率定时器(high-resolution timer)。
GetTickCount在.NET Framework中有一个对应项(counterpart)即:System.Environment.TickCount属性。TickCount属性在Environment类中定义如下:
publicstaticintTickCount {get;}
System.Environment.TickCount属性的值从系统计时器派生,并以 32 位有符号整数的形式存储。因此,如果系统连续运行 24.9 天,则运行时间将四舍五入到零位。TickCount 属性通过将其值重置为零来处理溢出状况。TickCount 返回的最小值为 0。MSDN上说TickCount 属性的分辨率不能小于 500 毫秒。我在程序中测试可以看出TickCount 的分辨率大概为15~16ms。测试代码如下[C#]:
using System;
namespace ConsoleApplication2
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
// TODO: 在此处添加代码以启动应用程序
for(int i=0;i<100;i++)
{
Console.WriteLine(i.ToString());
Console.WriteLine("start TickCount:" + System.Environment.TickCount.ToString());
System.Threading.Thread.Sleep(1);
Console.WriteLine("1ms elapsed TickCount:" + System.Environment.TickCount.ToString());
}
//pause for checking
System.Console.ReadLine();
}
}
}