[En-Nut-Discussion] NutGetTickClock rounding (again)

duane ellis ethernut at duaneellis.com
Wed Jul 16 05:00:14 CEST 2008


Henrik Maier wrote:
> Based on above I would refine my suggestion as follow:
>
> -----------------------------------------------------
> u_long NutTimerMillisToTicks(u_long ms)
> {
>    if (ms >= 0x3E8000UL) 
>       return (ms / 1000UL) * NutGetTickClock();
>    else
>       return (ms * NutGetTickClock() + 500UL - 1UL) / 1000UL; 
> }
> -----------------------------------------------------
>
>   
NO - i disagree.  I would call this *WRONG*  You are doing 'traditional 
rounding' at the 0.5 point. While mathematically that seems correct (ie: 
rounding money). Most developers Timeouts will be wrong 50% of the time.

For example - you know the old formula - convert N bits into N bytes... 
like this:  nbytes =   (nbits + 7) / 8

It is that "+7" that is important. You are suggesting nbytes = (nbits + 
4) / 8

The primary purpose of the function like this is to calculate a "timeout 
period in ticks". By rounding down as you suggest, the timeout period 
would be *WRONG*.

Timeout - or delay functions - traditionally have this attribute:

    DELAY for *at least* this many ticks. You may delay for longer -
    But never shorter then the requested period of time (unless an error 
of some type is returned).

Example:  

    "man 3 usleep" states: The actual time slept may be longer due to 
system latencies and possible limitations in the timer resolution of the 
hardware.

Likewise ' pthread_cond_timedwait" states:

    The /pthread_cond_timedwait/() function shall be equivalent to 
/pthread_cond_wait/(), except that an error is returned if the absolute 
time specified by /abstime/ passes (that is, system time equals or 
exceeds /abstime/) before the condition /cond/ is signaled or 
broadcasted, or if the absolute time specified by /abstime/ has already 
been passed at the time of the call.

Which quietly implies that the delay may be *LONGER* then the requested 
period - *never* shorter.

===

This same rule may apply for other reasons. You are a sleeping thread. 
Your timer has expired - you are now on the "ready que" - but there are 
higher priority tasks present.

-Duane.





More information about the En-Nut-Discussion mailing list