Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance precision and safety in time calculations #54

Merged
merged 2 commits into from
Sep 1, 2024

Conversation

visitorckw
Copy link
Contributor

Introduces a new inline function, mult_frac(), to handle fractional multiplication with improved precision and safety by computing x * n / d while avoiding common issues like overflow and precision loss. Additionally, the semu_timer_clocksource() function has been refactored to use mult_frac() for time-related calculations, including the calculations for converting time derived from clock_gettime() and mach_absolute_time() into clock ticks. These updates collectively enhance the accuracy and reliability of time computations throughout the codebase.

Introduce a new inline function mult_frac() to compute "x * n / d" with
enhanced precision and safety. This function addresses the common
issues of overflow and loss of precision that can occur with
straightforward approaches to this calculation.

Directly computing "x * n / d" can lead to problems:
- Performing the division first can result in loss of precision due to
  integer truncation.
- Performing multiplication before division can risk overflow.

The mult_frac() function mitigates these issues by:
1. Calculating the quotient and remainder of 'x' divided by 'd'.
2. Using these intermediate results to perform the final calculation,
   thus avoiding intermediate overflow and preserving precision.

This approach is based on the Linux kernel's mult_frac() macro [1],
which follows a similar method to handle these calculations robustly.

Link: https://elixir.bootlin.com/linux/v6.10.7/source/include/linux/math.h#L121 [1]
Enhance the semu_timer_clocksource() function by utilizing the
mult_frac() function to improve the precision of converting time to
clock ticks. This update refines the calculations for converting time
derived from clock_gettime() and mach_absolute_time() into clock ticks.
This ensures that the time-to-clock-ticks conversion is more reliable
and precise, addressing potential precision issues effectively.
@jserv jserv merged commit 0aceed0 into sysprog21:master Sep 1, 2024
2 checks passed
@jserv
Copy link
Collaborator

jserv commented Sep 1, 2024

Thank @visitorckw for contributing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants