math - Elapsed time of unsigned wrapping timer -
suppose have timer returns uint32_t value (representing number of ticks), counts upwards, , wraps 0 after reaching uint32_max. suppose need take elapsed time time a time b, , don't know how high timer might , whether wrap between a , b. both a , b type uint32_t , assigned timer's return value. correct statement can take (uint32_t)(b-a) elapsed time long no more uint32_max ticks have elapsed -- , correct if timer wrapped once? proof this?
let n = 232. let , b timestamps of start , end before wrapping [0, n) range, , assume ≤ b < + n. = % n , b = b % n. interested in computing duration d = b - a.
when ≤ b, trivial d = b - = b - a.
what when > b? ≤ b + n , must d = b - = b + n - a.
but b - of course congruent b + n - modulo n. since addition , subtraction between std::uint32_t modulo n, can safely compute answer d = b - a. subtraction operator between 2 std::uint32_t values std::uint32_t, there's no reason specify cast in (std::uint32_t)(b - a).
Comments
Post a Comment