程序计时及时间获取(Windows系统C++)

来源:互联网 发布:无尽武装听书软件 编辑:程序博客网 时间:2024/05/21 18:34
 对于相对高精度的计时:

使用供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 somethingQueryPerformanceCounter(&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 somethingtime_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';