From c31d6461982e3c1234c8af0bc1e58cdae3a25ac0 Mon Sep 17 00:00:00 2001 From: Nicolas Pitre Date: Wed, 6 Mar 2024 11:12:42 -0500 Subject: [PATCH] kernel: timeout: optimize z_timeout_expires() This currently calls timeout_rem() then adds back the result of elapsed() to cancel out the subtraction of another elapsed() call within timeout_rem(). Better not to make any calls to elapsed() in that case, especially given that elapsed() may incur hardware access overhead through sys_clock_elapsed(). Let's move the elapsed() subtraction to the only user of timeout_rem() that needs it and remove its invocation from the z_timeout_expires() path entirely. Signed-off-by: Nicolas Pitre --- kernel/timeout.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/kernel/timeout.c b/kernel/timeout.c index 29f15898035..b667abafe99 100644 --- a/kernel/timeout.c +++ b/kernel/timeout.c @@ -160,10 +160,6 @@ static k_ticks_t timeout_rem(const struct _timeout *timeout) { k_ticks_t ticks = 0; - if (z_is_inactive_timeout(timeout)) { - return 0; - } - for (struct _timeout *t = first(); t != NULL; t = next(t)) { ticks += t->dticks; if (timeout == t) { @@ -171,7 +167,7 @@ static k_ticks_t timeout_rem(const struct _timeout *timeout) } } - return ticks - elapsed(); + return ticks; } k_ticks_t z_timeout_remaining(const struct _timeout *timeout) @@ -179,7 +175,9 @@ k_ticks_t z_timeout_remaining(const struct _timeout *timeout) k_ticks_t ticks = 0; K_SPINLOCK(&timeout_lock) { - ticks = timeout_rem(timeout); + if (!z_is_inactive_timeout(timeout)) { + ticks = timeout_rem(timeout) - elapsed(); + } } return ticks; @@ -190,7 +188,10 @@ k_ticks_t z_timeout_expires(const struct _timeout *timeout) k_ticks_t ticks = 0; K_SPINLOCK(&timeout_lock) { - ticks = curr_tick + timeout_rem(timeout) + elapsed(); + ticks = curr_tick; + if (!z_is_inactive_timeout(timeout)) { + ticks += timeout_rem(timeout); + } } return ticks;