一、前言
这个东西比较简单,不废话,直接上代码
二、代码
2.1 Timer.h
#pragma once
#include <windows.h> // 包含BOOL与DWORD
#define RATE_MS_TO_SEC 1000 // 1s = 1000ms
class CTimer
{
public:
CTimer();
virtual ~CTimer();
void StartTimer();
BOOL TimeOver(long msTime);
long Get_secTime();
long Get_msTime();
private:
DWORD m_Start;
DWORD m_End;
};
2.2 Timer.cpp
#include "Timer.h"
CTimer::CTimer()
{
}
CTimer::~CTimer()
{
}
void CTimer::StartTimer(){
m_Start = GetTickCount64();
}
BOOL CTimer::TimeOver(long msTime) {
m_End = GetTickCount64();
if (m_End - m_Start >= msTime * RATE_MS_TO_SEC){
return TRUE;
}
return FALSE;
}
long CTimer::Get_secTime() {
m_End = GetTickCount64();
long temp = m_End - m_Start;
return temp / RATE_MS_TO_SEC;
}
long CTimer::Get_msTime(){
m_End = GetTickCount64();
long temp = m_End - m_Start;
return temp;
}
三、测试
3.1 测试代码
#include <iostream>
#include "Timer.h"
#define TIME_OUT 3 // 定时时间,3秒
using namespace std;
int main(){
CTimer timer;
timer.StartTimer();
cout << "timer1 开始定时...."<< endl;
do {
cout << "timer1 已定时 " << timer.Get_secTime() << " s" << endl;
cout << "timer1 已定时 " << timer.Get_msTime() << " ms" << endl;
} while (!timer.TimeOver(TIME_OUT));
cout << "timer1 定时时间到!" << endl;
cin.ignore();
return 0;
}