to find a elapsed time in a libevent timer before timer expiry

346 views Asked by At

I have a base code which has a libevent timer started for 480 seconds. After a delay, before the timer expiry, I wanted to find the number of seconds elapsed in that timer.

1

There are 1 answers

0
nickm On BEST ANSWER

There isn't a function that does that in libevent, and it wouldn't be super-easy to add one: right now, timers remember when they expire, but not when they were added.

(If you want to know when a timer will expire, you can get that with the event_pending() function.)

You could fake it pretty easily though, with something like this (untested) code:

struct annotated_timer {
    struct timeval tv;
    struct event *ev;
};

...

struct annotated_timer *
annotated_timer_new(void (*cb)(evutil_socket_t, short, void*), void *arg) {
    struct annotated_timer *at;
    if (!(at = malloc(sizeof(*at))))
        return NULL;
    if (!(at->ev = event_new(-1, 0, cb, arg))) {
        free(at);
        return NULL;
    }
    return at;
}
void
annotated_timer_add(struct annotated_timer *at, const struct timeval *tv) {
    evutil_gettimeofday(&at->tv, NULL);
    event_add(&at->ev, tv);
}
int
annotated_timer_get_time_waiting(struct annotated_timer *at, struct timeval *tv_out) {
    if (! event_pending(&at->ev, EV_TIMER, NULL))
        return -1;

    struct timeval now;
    evutil_gettimeofday(&now, NULL);
    evutil_timersub(tv_out, &now, &at->tv);
    return 0;
}