直接上代码:
#include <stdio.h>
#include <winsock2.h> // for GetTickCount
#include <windows.h> // for Sleep
int main()
{
int start = GetTickCount();
printf("%f\n", start / (3600000.0));// 操作系统运行到现在的时间
Sleep(2000);
int end = GetTickCount();
printf("%f\n", end / (3600000.0)); // 操作系统运行到现在的时间
printf("%d\n", end - start); // 2000
return 0;
}
注意, 如果写服务器程序, GetTickCount很容易造成错误。 理由如下(摘自百度):
GetTickcount函数:它返回从操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是2^32 ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0,MSDN中也明确的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是编写服务器端程序,此处一定要万分注意,避免引起意外的状况。
在超时时, 经常用到GetTickCount:
#include <stdio.h>
#include <winsock2.h> // for GetTickCount
int main()
{
int start = GetTickCount();
while(GetTickCount() - start < 10 * 1000) // 超时时间为10s
{
// ...
// 通常Sleep一下
}
int end = GetTickCount();
printf("%d\n", end - start); // 10000
return 0;
}