本文介绍了需要在c ++中以周期性的时间间隔调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在c ++中编写一个程序,我需要以周期性的时间间隔调用一个函数,例如每隔10ms。我从来没有做过与c ++中的时间或时钟相关的任何事情,这是一个快速而简单的问题,还是没有整洁解决方案的问题之一?
I am writing a program in c++ where I need to call a function at periodic time intervals, say every 10ms or so. I've never done anything related to time or clocks in c++, is this a quick and easy problem or one of those where there is no neat solution?
谢谢! / p>
Thanks!
推荐答案一个简单的计时器可以实现如下:
A simple timer can be implemented as follows,
#include <iostream> #include <chrono> #include <thread> #include <functional> void timer_start(std::function<void(void)> func, unsigned int interval) { std::thread([func, interval]() { while (true) { func(); std::this_thread::sleep_for(std::chrono::milliseconds(interval)); } }).detach(); } void do_something() { std::cout << "I am doing something" << std::endl; } int main() { timer_start(do_something, 1000); while(true); }这个简单的解决方案没有提供停止计时器的方法。计时器将继续运行,直到程序退出。
This simple solution does not offer a way to stop the timer. The timer will keep running until the program exited.
更多推荐
需要在c ++中以周期性的时间间隔调用函数
发布评论