[Asterisk-Dev] timeval stuff

Luigi Rizzo rizzo at icir.org
Wed Jun 8 01:55:48 MST 2005


Many of the asterisk sources use hand-rolled code to manipulate
struct timevals, including computing differences, sums, conversion
from/to millisecond values etc.

Apart from being ugly and making the code a lot longer than it
should be, the chances of screwing up in some computations (especially
on negative values) are extremely high.

If there are no objections I would like to replace these instances with
a set of functions, namely (names can be changed)

        struct timeval ast_tvnow()      /* returns the current timeofday */
        struct timeval ast_tv(int _s, int _us) /* converts s/us to timeval */
        struct timeval ast_ms2tv(int _ms) /* converts ms to timeval */
        long ast_mstvdiff(struct timeval a, struct timeval b)
                /* returns a-b in milliseconds */
        struct timeval ast_tvadd(struct timeval a, struct timeval b)
                /* adds two timevals */

These are derived from actual usage. Not sure if we need more.
ast_tv() is necessary as I don't think the compiler lets you construct
a struct on the fly while calling a function e.g.  foo( { sec, usec});

The reason i pass arguments by value and not by name is that this
way it is a lot simpler to write functions e.g. consider this chunk
of the diff:

-       gettimeofday(&rtp->dtmfmute, NULL);
-       rtp->dtmfmute.tv_usec += (500 * 1000);
-       if (rtp->dtmfmute.tv_usec > 1000000) {
-               rtp->dtmfmute.tv_usec -= 1000000;
-               rtp->dtmfmute.tv_sec += 1;
-       }
+       rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_ms2tv(500));

compared to the use of pointers, there is an extra copy of 64-bit values,
however 1) on modern machines that cost is probably negligible,
and 2) these things are generally associated to more expensive
computations, such as system calls etc. so i would not worry.

In case, we can always define inline the function and let
the compiler play his best tricks.

Opinions ?

	cheers
	luigi



More information about the asterisk-dev mailing list