精度 大约 1ms,但是毕竟还是有误差的
#include <stdio.h>
#include <Windows.h>
class CMySleep {
public:
CMySleep() {
InitializeConditionVariable(&cv);
InitializeCriticalSection(&cs);
}
~CMySleep() {
DeleteCriticalSection(&cs);
}
void operator()(DWORD nTime) {
SleepConditionVariableCS(&cv, &cs, nTime);
}
private:
CONDITION_VARIABLE cv;
CRITICAL_SECTION cs;
};
struct TimerStrcut {
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
};
class Timer {
public:
Timer() {
QueryPerformanceFrequency(&m_time.nFreq);
}
void Start() {
QueryPerformanceCounter(&m_time.nBeginTime);
}
void End() {
QueryPerformanceCounter(&m_time.nEndTime);
}
double GetTime() {
return (double)(m_time.nEndTime.QuadPart-m_time.nBeginTime.QuadPart) / (double)(m_time.nFreq.QuadPart);
}
private:
TimerStrcut m_time;
};
int main() {
CMySleep mySleep;
Timer time1;
time1.Start();
Sleep(1000);
time1.End();
printf("%.20lf\n", time1.GetTime());
time1.Start();
mySleep(1000);
time1.End();
printf("%.20lf\n", time1.GetTime());
return 0;
}