用了三种方法,第一种使用高精度性能计数器;第二种是使用多媒体定时器,另一种是《Windows图形编程》里提供的CPU周期来获取。推荐第一种方式测量:
先看第一种:
- #include <windows.h>
- #include <stdio.h>
-
- void main()
- {
- LARGE_INTEGER litmp;
- LONGLONG qt1,qt2;
- double dft,dff,dfm;
-
-
- QueryPerformanceFrequency(&litmp);
- dff=(double)litmp.QuadPart;
-
-
- QueryPerformanceCounter(&litmp);
- qt1=litmp.QuadPart;
-
-
- Sleep(1);
-
-
- QueryPerformanceCounter(&litmp);
- qt2=litmp.QuadPart;
-
-
- dfm=(double)(qt2-qt1);
- dft=dfm/dff;
-
-
- printf("用时: %.3f 毫秒\n", dft*1000.0);
- }
我的机器上为Sleep(1) = 0.454ms;Sleep(10) = 9.719ms;Sleep(100) = 99.541ms
下面是另外两种供参考:
- #include <stdio.h>
- #include <Windows.h>
- #include <Mmsystem.h>
- #include "timer.h"
-
- #pragma comment(lib, "winmm.lib")
-
-
- int i = 0;
- DWORD start;
- DWORD end;
-
- #define TIMES (1000)
-
- void main()
- {
-
-
-
-
-
-
- ::timeBeginPeriod(1);
- Sleep(100);
-
-
- start = ::timeGetTime();
- for (i=0; i<TIMES; i++)
- {
- Sleep(1);
- }
-
-
- end = ::timeGetTime();
- printf("使用高精度定时器测试Sleep(1)时间: %.3f ms\n", (end-start)/((double)TIMES));
-
-
-
-
-
-
-
-
- KTimer timer;
-
-
- timer.Start();
- Sleep(1000);
- unsigned __int64 cpuspeed = (unsigned)(timer.Stop()/1000000);
- printf("CPU速度: %I64d MHz\n", cpuspeed);
-
-
-
- timer.Start();
-
- Sleep(1);
-
-
- unsigned __int64 time = (unsigned) timer.Stop();
- printf("使用CPU周期数测得Sleep(1)时间: %I64d μs\n", time/cpuspeed);
-
-
-
-
-
- ::timeEndPeriod(1);
-
-
- }