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

faster rand(::Tuple) #32208

Merged
merged 2 commits into from
Sep 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion stdlib/Random/src/RNGs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ end
#### from a range

for T in BitInteger_types, R=(1, Inf) # eval because of ambiguity otherwise
@eval Sampler(::Type{MersenneTwister}, r::UnitRange{$T}, ::Val{$R}) =
@eval Sampler(::Type{MersenneTwister}, r::AbstractUnitRange{$T}, ::Val{$R}) =
SamplerRangeFast(r)
end

Expand Down
33 changes: 19 additions & 14 deletions stdlib/Random/src/generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -464,20 +464,25 @@ function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C}}) where {A,B,C}
@inbounds return sp[][1 + r ÷ 0x0005555555555555]
end

### 4

Sampler(RNG::Type{<:AbstractRNG}, t::Tuple{A,B,C,D}, n::Repetition) where {A,B,C,D} =
SamplerSimple(t, Sampler(RNG, UInt52Raw(Int), n))

function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C,D}}) where {A,B,C,D}
r = rand(rng, sp.data) & 3
@inbounds return sp[][1 + r]
end

### n

Sampler(RNG::Type{<:AbstractRNG}, t::Tuple, n::Repetition) =
SamplerSimple(t, Sampler(RNG, Base.OneTo(length(t)), n))
@generated function Sampler(RNG::Type{<:AbstractRNG}, t::Tuple, n::Repetition)
l = fieldcount(t)
if l < typemax(UInt32) && ispow2(l)
:(SamplerSimple(t, Sampler(RNG, UInt32, n)))
else
:(SamplerSimple(t, Sampler(RNG, Base.OneTo(length(t)), n)))
end
end

rand(rng::AbstractRNG, sp::SamplerSimple{<:Tuple}) =
@inbounds return sp[][rand(rng, sp.data)]
@generated function rand(rng::AbstractRNG, sp::SamplerSimple{T}) where T<:Tuple
l = fieldcount(T)
if l < typemax(UInt32) && ispow2(l)
quote
r = rand(rng, sp.data) & ($l-1)
@inbounds return sp[][1 + r]
end
else
:(@inbounds return sp[][rand(rng, sp.data)])
end
end