本文提供的代码可以准确显示实时的时间,并且每一秒都会显示一次。但仍然略有延迟,原因是代码运行消耗的时间并没有完全考虑进去。
#include <iostream>
#include <time.h>
#include <iomanip> //setw(), setfill()
#include <thread>
#include <chrono>
using namespace std;
class Clock
{
public:
Clock()
{
time_t t = time(nullptr);
struct tm* pt = localtime(&t);
_sec = pt->tm_sec;
_min = pt->tm_min;
_hour = pt->tm_hour;
}
void run();
private:
void display()
{
system("cls");
cout << setfill('0')
<< setw(2) << _hour << ":"
<< setw(2) << _min << ":"
<< setw(2) << _sec << endl;
}
void getLocalTime() //见说明1
{
time_t t = time(nullptr);
struct tm* pt = localtime(&t);
_sec = pt->tm_sec;
_min = pt->tm_min;
_hour = pt->tm_hour;
}
int _sec;
int _min;
int _hour;
};
void Clock::run()
{
while(1)
{
clock_t start = clock();
getLocalTime();
display();
clock_t finish = clock();
//sleepCertainTimeToPassOneSecond
this_thread::sleep_for(chrono::milliseconds(1000-(finish - start))); //见说明2
}
}
int main() {
Clock c;
c.run();
system("pause");
return 0;
}
说明:
- getLocalTime()函数获取本地时间,并通过display()函数显示。为什么不选择sleep(1)来模拟时钟走过一秒呢?因为代码运行会消耗时间,导致模拟走过1秒实际是走过了>1s,时间显示会越来越不准确。而每次显示都是本地时间则不会出现显示的时间不准确的情况。
- 通过clock()函数来获取代码运行消耗的时间,从而尽量保证每一秒都会显示,不会出现跳过一秒的情况。