chTimeIsWithin()

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
genosensor
Posts: 65
Joined: Thu Oct 03, 2013 1:06 am
Has thanked: 1 time
Been thanked: 1 time

chTimeIsWithin()

Post by genosensor »

chTimeIsWithin() is defined in kernel/src/chvt.c as:

Code: Select all

bool_t chTimeIsWithin(systime_t start, systime_t end) {
  systime_t time = chTimeNow();
  return end > start ? (time >= start) && (time < end) :
                       (time >= start) || (time < end);
}

Could not this function be more efficiently to redefined as (a simple macro)?:

Code: Select all

#define chTimeIsWithin(start, end)  \
  (chTimeNow()-(start) < ((end) - (start)))

Subtracting start from the chTimeNow() deals with the possible time wrap around without conditional branching and multiple tests. Moreover, usually, one is just trying to determine whether more than a certain number of limitTics has elapsed since a given start time. The test for that is even simpler:

Code: Select all

//return the number of tics since start time
#define chTimeElapsedSince(start) (chTimeNow()-(start))

The test becomes:

Code: Select all

  chTimeElapsedSince(start) < limitTics

and the original chTimeIsWithin() test becomes:

Code: Select all

#define chTimeIsWithin(start, end)  chTimeElapsedSince(start) < ((end)-(start))

Just wondering what I'm missing.
Is there some case where this simpler logic is not equivalent to the existing chTimeIsWithin()?
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: chTimeIsWithin()

Post by Giovanni »

Hi,

I don't see problems, excellent suggestion, it is a pretty critical bit of code.

Giovanni
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: chTimeIsWithin()

Post by Giovanni »

Hi,

Applied the change to both stable and unstable versions, thanks.

Giovanni
Post Reply