Skip to content

Commit e7d5905

Browse files
nordic-krchkartben
authored andcommitted
kernel: timeout: Reduce number of sys_clock_elapsed calls
sys_clock_elapsed requires access to system clock register interface which is often slow. When new relative timeout is added sys_clock_elapsed() is called once to calculate delta ticks and then if that triggers setting new timeout sys_clock_elapsed() is called again. This call is redundant since everything happens under spin lock so it is better to reuse value returned by the first call. Signed-off-by: Krzysztof Chruściński <[email protected]>
1 parent 83f877a commit e7d5905

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

kernel/timeout.c

+16-7
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,9 @@ static int32_t elapsed(void)
8484
return announce_remaining == 0 ? sys_clock_elapsed() : 0U;
8585
}
8686

87-
static int32_t next_timeout(void)
87+
static int32_t next_timeout(int32_t ticks_elapsed)
8888
{
8989
struct _timeout *to = first();
90-
int32_t ticks_elapsed = elapsed();
9190
int32_t ret;
9291

9392
if ((to == NULL) ||
@@ -116,9 +115,13 @@ void z_add_timeout(struct _timeout *to, _timeout_func_t fn,
116115

117116
K_SPINLOCK(&timeout_lock) {
118117
struct _timeout *t;
118+
int32_t ticks_elapsed;
119+
bool has_elapsed = false;
119120

120121
if (Z_IS_TIMEOUT_RELATIVE(timeout)) {
121-
to->dticks = timeout.ticks + 1 + elapsed();
122+
ticks_elapsed = elapsed();
123+
has_elapsed = true;
124+
to->dticks = timeout.ticks + 1 + ticks_elapsed;
122125
} else {
123126
k_ticks_t ticks = Z_TICK_ABS(timeout.ticks) - curr_tick;
124127

@@ -139,7 +142,13 @@ void z_add_timeout(struct _timeout *to, _timeout_func_t fn,
139142
}
140143

141144
if (to == first() && announce_remaining == 0) {
142-
sys_clock_set_timeout(next_timeout(), false);
145+
if (!has_elapsed) {
146+
/* In case of absolute timeout that is first to expire
147+
* elapsed need to be read from the system clock.
148+
*/
149+
ticks_elapsed = elapsed();
150+
}
151+
sys_clock_set_timeout(next_timeout(ticks_elapsed), false);
143152
}
144153
}
145154
}
@@ -155,7 +164,7 @@ int z_abort_timeout(struct _timeout *to)
155164
remove_timeout(to);
156165
ret = 0;
157166
if (is_first) {
158-
sys_clock_set_timeout(next_timeout(), false);
167+
sys_clock_set_timeout(next_timeout(elapsed()), false);
159168
}
160169
}
161170
}
@@ -210,7 +219,7 @@ int32_t z_get_next_timeout_expiry(void)
210219
int32_t ret = (int32_t) K_TICKS_FOREVER;
211220

212221
K_SPINLOCK(&timeout_lock) {
213-
ret = next_timeout();
222+
ret = next_timeout(elapsed());
214223
}
215224
return ret;
216225
}
@@ -257,7 +266,7 @@ void sys_clock_announce(int32_t ticks)
257266
curr_tick += announce_remaining;
258267
announce_remaining = 0;
259268

260-
sys_clock_set_timeout(next_timeout(), false);
269+
sys_clock_set_timeout(next_timeout(0), false);
261270

262271
k_spin_unlock(&timeout_lock, key);
263272

0 commit comments

Comments
 (0)