Ordinary rejection sampling is faster than what random-natural does
#111
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
My Herbie project spends about 3–4% of runtime in the
random-naturalfunction. This lead me to look at how that function works, and in fact instead of ordinary rejection sampling, it implements a clever algorithm that biases the sampling slightly to reduce the rejection probability. But that biasing involves a bignum multiplication, and after timing it, it looks to be quite a bit slower than ordinary rejection sampling. Specifically, I ran this code for timing:You can see that it samples a natural number below
197823238423487and measures its runtime in nanoseconds/iter. I get 190–200 nanoseconds for ordinary rejection sampling and 400–410 nanoseconds for the clever version. I say we go back to the ordinary version.