0 c++ precision clock scheduled-tasks
我想以不同的时间间隔安排任务:0.1秒,0.9s ...... 2s等我使用clock()C++函数返回自模拟开始以来的刻度数,并将刻度数转换为秒使用CLOCKS_PER_SEC但是我注意到当Instant是float时没有调度任务,但是当它是一个整数时它就会被调度.这里负责调度的代码部分:
float goal = (float) clock() / CLOCKS_PER_SEC + 0.4 ; // initially (float) clock() / CLOCKS_PER_SEC = 0 ;
if ((float) clock() / CLOCKS_PER_SEC == goal)
do stuff ;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它不起作用,但是当我计划在3秒内完成任务时,例如它可以工作.这是一个精度问题吗?
Som*_*ude 13
如果我是在实现C++一些定时器机制,我很可能会使用std::chrono命名空间一起std::priority_queue.
#include <functional>
#include <queue>
#include <chrono>
#include <sys/time.h> // for `time_t` and `struct timeval`
namespace events
{
struct event
{
typedef std::function<void()> callback_type;
typedef std::chrono::time_point<std::chrono::system_clock> time_type;
event(const callback_type &cb, const time_type &when)
: callback_(cb), when_(when)
{ }
void operator()() const
{ callback_(); }
callback_type callback_;
time_type when_;
};
struct event_less : public std::less<event>
{
bool operator()(const event &e1, const event &e2) const
{
return (e2.when_ < e1.when_);
}
};
std::priority_queue<event, std::vector<event>, event_less> event_queue;
void add(const event::callback_type &cb, const time_t &when)
{
auto real_when = std::chrono::system_clock::from_time_t(when);
event_queue.emplace(cb, real_when);
}
void add(const event::callback_type &cb, const timeval &when)
{
auto real_when = std::chrono::system_clock::from_time_t(when.tv_sec) +
std::chrono::microseconds(when.tv_usec);
event_queue.emplace(cb, real_when);
}
void add(const event::callback_type &cb,
const std::chrono::time_point<std::chrono::system_clock> &when)
{
event_queue.emplace(cb, when);
}
void timer()
{
event::time_type now = std::chrono::system_clock::now();
while (!event_queue.empty() &&
(event_queue.top().when_ < now))
{
event_queue.top()();
event_queue.pop();
}
}
}
Run Code Online (Sandbox Code Playgroud)
要使用,只需使用添加事件events::add,并events::timer每秒调用几次.
例:
void foo()
{
std::cout << "hello from foo\n";
}
void done()
{
std::cout << "Done!\n";
}
struct bar
{
void hello()
{ std::cout << "Hello from bar::hello\n"; }
};
auto now = std::chrono::system_clock::now();
bar b;
events::add(foo, now + std::chrono::seconds(2));
events::add(std::bind(&bar::hello, b), now + std::chrono::seconds(4));
events::add(done, now + std::chrono::seconds(6));
while (true)
{
usleep(10000);
events::timer();
}
Run Code Online (Sandbox Code Playgroud)
以上示例将打印:
hello from foo hello from bar::hello Done!
每两秒打印一行.后"Done!"程序只会永远循环下去,什么都不做.
请注意,该程序包含许多C++ 11功能,但已经过GCC 4.4.5和4.7.1的测试.不幸的是,VC++ 2010没有<chrono>标题,但VC++ 2012RC显然拥有它.
| 归档时间: |
|
| 查看次数: |
5539 次 |
| 最近记录: |