在C++11中实现高精度定时器的最佳方式是什么,该定时器在循环中不断检查时间,并在经过某个时间点后执行一些代码?例如,检查从上午9点开始循环的时间,并在上午11点准确地执行一些代码我要求时间精确(即上午9点后不超过1微秒)。
我将在LinuxCPU7.3上实现这个程序,使用专门的CentOS资源来执行这个任务是没有问题的。
发布于 2019-09-16 16:06:55
你可以使用systemd.timer
,而不是手动实现。确保指定the desired accuracy,它显然可以精确到1us。
发布于 2019-09-16 22:19:49
在循环中连续检查时间的高分辨率定时器,
首先,你不想()不断地检查循环中的时间;这是非常低效的,而且是不必要的。
在经过某个时间点后,
...executes一些代码?
好的,所以你想在将来的某个时间尽可能准确地运行一些代码。
最简单的方法是简单地启动一个后台线程,计算离目标时间还有多长时间(以所需的分辨率),然后让线程在该时间段内休眠。当你的线程被唤醒时,它会执行实际的任务。这应该足够准确,以满足绝大多数需求。
std::chrono
库提供的调用使这一点变得很容易:
下面是一段代码,它使用系统时钟执行您想要的操作(这使得设置挂钟时间变得更容易):
// c++ --std=c++11 ans.cpp -o ans
#include <thread>
#include <iostream>
#include <iomanip>
// do some busy work
int work(int count)
{
int sum = 0;
for (unsigned i = 0; i < count; i++)
{
sum += i;
}
return sum;
}
std::chrono::system_clock::time_point make_scheduled_time (int yyyy, int mm, int dd, int HH, int MM, int SS)
{
tm datetime = tm{};
datetime.tm_year = yyyy - 1900; // Year since 1900
datetime.tm_mon = mm - 1; // Month since January
datetime.tm_mday = dd; // Day of the month [1-31]
datetime.tm_hour = HH; // Hour of the day [00-23]
datetime.tm_min = MM;
datetime.tm_sec = SS;
time_t ttime_t = mktime(&datetime);
std::chrono::system_clock::time_point scheduled = std::chrono::system_clock::from_time_t(ttime_t);
return scheduled;
}
void do_work_at_scheduled_time()
{
using period = std::chrono::system_clock::period;
auto sched_start = make_scheduled_time(2019, 9, 17, // date
00, 14, 00); // time
// Wait until the scheduled time to actually do the work
std::this_thread::sleep_until(sched_start);
// Figoure out how close to scheduled time we actually awoke
auto actual_start = std::chrono::system_clock::now();
auto start_delta = actual_start - sched_start;
float delta_ms = float(start_delta.count())*period::num/period::den * 1e3f;
std::cout << "worker: awoken within " << delta_ms << " ms" << std::endl;
// Now do some actual work!
int sum = work(12345);
}
int main()
{
std::thread worker(do_work_at_scheduled_time);
worker.join();
return 0;
}
在我的笔记本电脑上,典型的延迟大约是2-3ms。如果你使用high_resolution_clock
,你应该能够得到更好的结果。
您还可以使用其他API,例如Boost,您可以在其中使用use ASIO to implement high res timeout。
I要求计时精确(即上午9点后不超过1微秒)。
你真的需要精确到微秒吗?考虑到在此分辨率下,您还需要考虑各种其他因素,包括系统负载、延迟、时钟抖动等。您的代码可以在接近那个时间开始执行,但这只是问题的一部分。
发布于 2019-09-16 20:02:29
我的建议是使用timer_create()。这使您可以在给定的时间收到信号的通知。然后您可以在signal handler中实现您的操作。
在任何情况下,您都应该意识到准确性当然取决于系统时钟的准确性。
https://stackoverflow.com/questions/57952601
复制相似问题