gpt4 book ai didi

c++ - QT ntp 和摆脱差异

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:43:24 27 4
gpt4 key购买 nike

我从另一个用户那里得到代码 link

我连接到:pool.ntp.org

但我不能在时间上有任何差异。 (我需要与 ntp 服务器完美同步 - 然后我会很高兴)

我的代码:

time_t t = response.tx.to_time_t();
char *s = ctime(&t);

WSACleanup();

h_qtimeonStatusBar->setDateTime(QDateTime::fromTime_t(response.tx.to_time_t()));

但首先我有这段代码:

getNTPTime(); //function above
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime())); // update time = current time from 'getNTPTime()' + 1 s
timer->start(0);
timer->setInterval(1000);

我的差异以毫秒为单位(最大 1000),但它确实是可见的。我的时钟比ntp服务器慢一点(这是可靠的信息)

如何消除这种差异?

我试试看:

//func run after program start
{
getNTPTime();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()));
timer->start(0);
timer->setInterval(1000);
}


bool plemionabot1::getNTPTime(){
using namespace std::chrono;
WSADATA wsaData;
DWORD ret = WSAStartup(MAKEWORD(2, 0), &wsaData);
char *host = "pool.ntp.org"; /* Don't distribute stuff pointing here, it's not polite. */
//char *host = "time.nist.gov"; /* This one's probably ok, but can get grumpy about request rates during debugging. */

NTPMessage msg;
/* Important, if you don't set the version/mode, the server will ignore you. */
msg.clear();
msg.version = 3;
msg.mode = 3 /* client */;

NTPMessage response;
response.clear();

int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in srv_addr;
memset(&srv_addr, 0, sizeof(srv_addr));
msg.dns_lookup(host, &srv_addr); /* Helper function defined below. */

msg.sendto(sock, &srv_addr);
auto t0 = high_resolution_clock::now();
response.recv(sock);
time_t t = response.tx.to_time_t();
char *s = ctime(&t);

WSACleanup();
//QDateTime * tmp = new QDateTime;
//tmp->setMSecsSinceEpoch(response.tx.seconds); // time is too much
//h_qtimeonStatusBar->setDateTime(tmp->currentDateTime());
h_qtimeonStatusBar->setDateTime(QDateTime::fromTime_t(response.tx.to_time_t())); // tą opcją wychodzi za mało
auto t1 = high_resolution_clock::now();
h_qtimeonStatusBar->setTime(h_qtimeonStatusBar->time().addMSecs(duration_cast<milliseconds>(t1-t0).count())); // time not enough
return true;
}

最佳答案

来自QTimer documentation :

Accuracy and Timer Resolution

Timers will never time out earlier than the specified timeout value and they are not guaranteed to time out at the exact value specified. In many situations, they may time out late by a period of time that depends on the accuracy of the system timers.

您不能依赖 QTimer 来为您保持准确的时间。

相反,您需要做的是计算自上次查询 NTP 服务器以来的已用时间。耗时基于您的系统时钟,它也可能会漂移,但这不是同一个问题。获取自查询 NTP 服务器以来耗时,并将其添加到从查询 NTP 服务器开始的系统时钟时间,以更好地估计当前 NTP 时间。

更好的方法是设置 ntpd,以便您的系统时钟自动调整为 NTP 时间。那么你的应用程序就不用担心这个了,你可以简单地显示系统时间。

关于c++ - QT ntp 和摆脱差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25129871/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com