Skip to content

Commit 10bde69

Browse files
committed
extmod/utime_mphal: ticks_diff(): Optimize to avoid if conditions.
1 parent 5fae914 commit 10bde69

1 file changed

Lines changed: 4 additions & 6 deletions

File tree

extmod/utime_mphal.c

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,10 @@ STATIC mp_obj_t time_ticks_diff(mp_obj_t end_in, mp_obj_t start_in) {
8989
// we assume that the arguments come from ticks_xx so are small ints
9090
uint32_t start = MP_OBJ_SMALL_INT_VALUE(start_in);
9191
uint32_t end = MP_OBJ_SMALL_INT_VALUE(end_in);
92-
int32_t diff = end - start;
93-
if (diff < (signed)-(MICROPY_PY_UTIME_TICKS_PERIOD / 2)) {
94-
diff += MICROPY_PY_UTIME_TICKS_PERIOD;
95-
} else if (diff >= (signed)(MICROPY_PY_UTIME_TICKS_PERIOD / 2)) {
96-
diff -= MICROPY_PY_UTIME_TICKS_PERIOD;
97-
}
92+
// Optimized formula avoiding if conditions. We adjust difference "forward",
93+
// wrap it around and adjust back.
94+
int32_t diff = ((end - start + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1))
95+
- MICROPY_PY_UTIME_TICKS_PERIOD / 2;
9896
return MP_OBJ_NEW_SMALL_INT(diff);
9997
}
10098
MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff);

0 commit comments

Comments
 (0)