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

Divide by Constant Optimization #35

Open
NCGThompson opened this issue Nov 13, 2023 · 2 comments
Open

Divide by Constant Optimization #35

NCGThompson opened this issue Nov 13, 2023 · 2 comments

Comments

@NCGThompson
Copy link
Contributor

We expect the compiler to look for redundant division and remainder operations on primitive types, and replace those with a single division. However, the compiler doesn't do this for ethnum's types, so ethnum has a separate divrem function. Following that same reasoning, it would make sense to provide a separate function for dividing by small compile time constants.

This is particularly useful for printing a big number in base 10.

@nlordell
Copy link
Owner

nlordell commented Nov 16, 2023

Just to make sure I understood the issue correctly, this would provide U256::div_u64(divisor: u64) functions that don’t needlessly compute the remainder? Or do you mean provide a const fn U256::div_64?

@NCGThompson
Copy link
Contributor Author

The div_rem mention was just an analogy. It doesn't need to be a const function, but it takes advantage of precomputation when the divisor is known but not the dividend. Here is a widget showing how it works.

If I understand it correctly, then the precomputation cost is only dependent on the divisor, not the dividend, so dividing by constants that fit in a usize is particularily effecient. I experimented with compiler explorer some, and on x86_64, a hand written 256 x 64 multiplication yields good assembly without any LLVM-IR usage or nightly-only functions.

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

No branches or pull requests

2 participants