对于相对高精度的计时:
使用供WIN9X使用的高精度定时器:QueryPerformanceFrequency()和QueryPerformanceCounter(),要求计算机从硬件上支持高精度定时器。需包含windows.h头文件。
//需要包含<windows.h> 头文件
#include <windows.h>
LARGE_INTEGER time_start, time_end;
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);//获取处理频率
QueryPerformanceCounter(&time_start); //获取起始时间
//do something
QueryPerformanceCounter(&time_end); //获取终止时间
cout<<time_end.u.HighPart<<' '<<time_end.u.LowPart<<endl;
//VC6.0的环境不支持直接"cout<<"64位的整数
printf("It's used %I64d, the frequency is %I64dHz/s\n",
time_end.QuadPart - time_start.QuadPart, frequency);
//耗时计算公式(运算结果为秒):
//((time_end.QuadPart-time_start.QuadPart)/frequency.QuadPart)
//具体用法可以参考更详细的资料
相对较低精度的时间获取使用用clock():
#include <time.h>
clock_t time_start, time_end;
time_start = clock();
//do something
time_end = clock();
printf("It's used %dms.\n", time_end - time_start);//结果以毫秒表示
关于获取当前时间:
//获取系统时间
SYSTEMTIME stime;
GetLocalTime(&stime);
//GetSystemTime(&stime); //得到Coordinated Universal Time (UTC),存在时差
cout<<"time: "<<stime.wYear<<'-'<<stime.wMonth<<'-'<<stime.wDay
<<' '<<stime.wHour<<':'<<stime.wMinute<<':'<<stime.wSecond<<'\n';