2

我需要一个计时器来执行分辨率相对较低的回调。在 Linux 中实现此类 C++ 计时器类的最佳方法是什么?有没有我可以使用的库?

4

5 回答 5

14

如果您在框架(Glib、Qt、Wx、...)中编写,您将已经拥有一个具有定时回调功能的事件循环。我会假设情况并非如此。

如果您正在编写自己的事件循环,则可以将gettimeofday/select对(struct timeval,微秒精度)或clock_gettime/nanosleep对(struct timespec,纳秒精度)用于您自己的事件调度程序。尽管后一个界面的分辨率更高,但调度永远不会那么准确,所以选择最适合的。

#include <algorithm>
#include <functional>
#include <vector>

#include <errno.h>
#include <sys/time.h>
#include <unistd.h>

using namespace std;

class scheduler {
public:
    scheduler();
    int events();
    void addEvent(const struct timeval, int (*)(void *), void *);
    int dispatchUntil(const struct timeval &);
    bool waitUntil(const struct timeval * = NULL);
    int loopUntil(const struct timeval * = NULL);

private:
    static bool tv_le(const struct timeval &, const struct timeval &);
    struct event {
        struct timeval when;
        int (*callback)(void *);
        void *data;
    };
    static struct _cmp
      : public binary_function<bool, const struct event &, const struct event &>
    {
        bool operator()(const struct event &a, const struct event &b) {
            return !tv_le(a.when, b.when);
        }
    } cmp;
    vector<struct event> heap;
};

bool scheduler::tv_le(const struct timeval &a, const struct timeval &b) {
    return a.tv_sec < b.tv_sec ||
        a.tv_sec == b.tv_sec && a.tv_usec <= b.tv_usec;
}

scheduler::scheduler() : heap() {}

int scheduler::events() {
    return heap.size();
}

void scheduler::addEvent(const struct timeval when, int (*callback)(void *), void *data) {
    struct event ev = {when, callback, data};
    heap.push_back(ev);
    push_heap(heap.begin(), heap.end(), cmp);
}

int scheduler::dispatchUntil(const struct timeval &tv) {
    int count = 0;
    while (heap.size() > 0 && tv_le(heap.front().when, tv)) {
        struct event ev = heap.front();
        pop_heap(heap.begin(), heap.end(), cmp);
        heap.pop_back();
        ev.callback(ev.data);
        count++;
    }
    return count;
}

bool scheduler::waitUntil(const struct timeval *tv) {
    if (heap.size() > 0 && (!tv || tv_le(heap.front().when, *tv)))
        tv = &heap.front().when;
    if (!tv)
        return false;
    struct timeval tv2;
    do {
        gettimeofday(&tv2, NULL);
        if (tv_le(*tv, tv2))
            break;
        tv2.tv_sec -= tv->tv_sec;
        if ((tv2.tv_usec -= tv->tv_usec) < 0) {
            tv2.tv_sec--;
            tv2.tv_usec += 1000000;
        }
    } while (select(0, NULL, NULL, NULL, &tv2) < 0 && errno == EINTR);
    return heap.size() > 0 && tv_le(*tv, heap.front().when);
}

int scheduler::loopUntil(const struct timeval *tv) {
    int counter = 0;
    while (waitUntil(tv))
        counter += dispatchUntil(heap.front().when);
    return counter;
}

警告:我喜欢 C。我从不写 C++。我只是假装懂语言。

免责声明:刚刚写的,完全未经测试。基本思想是将事件保存在优先级队列中,等到第一个,运行它,然后重复。

于 2009-02-03T03:50:42.720 回答
7

使用 boost::asio 库。它具有调用回调的同步和异步计时器。

http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial.html

于 2009-02-02T18:29:51.277 回答
0

试试 time.h 中定义的 clock_gettime() 函数:

int clock_gettime(clockid_t clk_id, struct timespec *tp);

struct timespec {
  time_t   tv_sec;        /* seconds */
  long     tv_nsec;       /* nanoseconds */
};

通常你可以这样称呼它:

struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
于 2009-02-02T18:19:37.647 回答
0

time.h 标头中的 timeval 结构是您正在寻找的。它有以秒和纳秒为单位的时间。所以以纳秒为单位的总时间是 timeval.tv_sec * 1000000 + timeval.tv_usec。很简单,我想。

#include <time.h>
timeval theStartTime;
gettimeofday(&theStartTime);
std::cout<<"The time we got's seconds field = "<<theStartTime.tv_sec<<std::endl;
std::cout<<"The time we got's nanoseconds field =  "<<theStartTime.tv_usec<<std::endl;
于 2009-02-02T18:31:44.347 回答
0

这是一个计时器类的链接。您只需要创建计时器并将其值传递给自动重新加载或不。指向回调函数的指针。如果您希望它由线程或信号处理。如果您选择信号,那么您也必须通过信号。

http://timerlinux.codeplex.com/

如果你想学习更多关于定时器或信号的知识,有一本好书叫做 linux 系统编程。您只需要阅读 3 章并对其进行解释。

于 2009-06-16T15:32:08.950 回答