Skip to content

k_uptime_delta(): Defective by design #16195

@pizi-nordic

Description

@pizi-nordic

The k_uptime_delta() API is widely used in Zephyr tests. However due to flaw in the design, the values returned by k_uptime_delta() depends on the uptime of the system if (1000 / CONFIG_SYS_CLOCK_TICKS_PER_SEC) is not an integer. As result, multiple tests are failing (example: #15983).

Cause:
The k_uptime_delta() calculates delta time using two timestamps (expressed in milliseconds) obtained form the system uptime (measured in system ticks). Unfortunately, the uptime conversion from ticks to milliseconds is inaccurate when (1000 / CONFIG_SYS_CLOCK_TICKS_PER_SEC) is not an integer. The rounding, which is applied in such case, leads to errors in delta time calculation.

Example (for CONFIG_SYS_CLOCK_TICKS_PER_SEC = 128):

Tick Uptime [ms] k_uptime_get() Delta time from previous tick returned by k_uptime_delta()
0 0,000 0
1 7,813 7 7
2 15,625 15 8
3 23,438 23 8
4 31,250 31 8
5 39,063 39 8
6 46,875 46 7
7 54,688 54 8
8 62,500 62 8
9 70,313 70 8
10 78,125 78 8

Please note, that ticks 1 and 6 are reported as shorter than others, which is not true.

Possible solution:
The k_uptime_delta() API in current form cannot be fixed. The reference time has to be stored in ticks (or other unit used by kernel) and all calculations should be performed using this unit. Only the result of calculations should be converted to ms.

Metadata

Metadata

Assignees

Labels

Stalearea: APIChanges to public APIsarea: KernelbugThe issue is a bug, or the PR is fixing a bugpriority: lowLow impact/importance bug

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions