[
https://issues.apache.org/jira/browse/RNG-57?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16627255#comment-16627255
]
Alex D Herbert commented on RNG-57:
-----------------------------------
For reference this is what I tried:
{code:java}
/**
* Wrap an IntProvider instance to enable fast provision of
* {@link UniformRandomProvider#nextBoolean()}.
*/
final static class CachedIntProvider
extends IntProvider
implements CachedUniformRandomProvider {
/** The underlying source of randomness. */
protected final UniformRandomProvider rng;
/**
* The cached value from a call to random UniformRandomProvider#nextInt().
*
* <p>Provides a bit source for booleans.
*/
private int booleanSource; // Initialised as 0
/**
* The bit mask of the boolean source to obtain the boolean bit.
*
* <p>The bit mask contains a single bit set.
* This begins at the least significant bit and is gradually shifted
* upwards until overflow to zero.
*/
private int booleanBitMask; // Initialised as 0
/**
* Create a new instance.
*
* @param rng the source of randomness
*/
CachedIntProvider(IntProvider rng) {
this.rng = rng;
}
@Override
public int next() {
// Delegate this
return rng.nextInt();
}
@Override
public boolean nextBoolean() {
if (booleanBitMask == 0) {
// Get the next value
booleanSource = next();
booleanBitMask = 1;
}
final boolean next = (booleanSource & booleanBitMask) == 0;
// Shift up. This will eventually overflow and become zero.
booleanBitMask <<= 1;
return next;
}
}
{code}
> CachedUniformRandomProvider for nextBoolean() and nextInt()
> -----------------------------------------------------------
>
> Key: RNG-57
> URL: https://issues.apache.org/jira/browse/RNG-57
> Project: Commons RNG
> Issue Type: Improvement
> Components: sampling
> Affects Versions: 1.2
> Reporter: Alex D Herbert
> Priority: Minor
> Labels: performance
>
> Implement a wrapper around a {{UniformRandomProvider}} that can cache the
> underlying source of random bytes for use in the methods {{nextBoolean()}}
> and {{nextInt()}} (in the case of {{LongProvider}}). E.g.
> {code:java}
> LongProvider provider = RandomSource.create(RandomSource.SPLIT_MIX_64);
> CachedLongProvider rng = new CachedLongProvider(provider);
> // Uses cached nextLong() 64 times
> rng.nextBoolean();
> // Uses cached nextLong() twice
> rng.nextInt();
> IntProvider provider = RandomSource.create(RandomSource.KISS);
> CachedIntProvider rng2 = new CachedIntProvider(provider);
> // Uses cached nextInt() 32 times
> rng2.nextBoolean();
> // This could be wrapped by a factory method:
> UniformRandomProvider rng = CachedUniformRandomProviderFactory.wrap(
> // Any supported source: IntProvider or LongProvider
> RandomSource.create(RandomSource...));
> {code}
> The implementation should be speed tested to determine the benefit for
> {{nextBoolean()}} and if {{nextInt()}} can be improved for {{LongProviders}}.
--
This message was sent by Atlassian JIRA
(v7.6.3#76005)