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

Speeding up Random.Shuffle by batching #111015

Closed
wants to merge 5 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ public override float NextSingle()
public override void NextBytes(byte[] buffer) => _prng.NextBytes(buffer);

public override void NextBytes(Span<byte> buffer) => _prng.NextBytes(buffer);

public override void Shuffle<T>(Span<T> values)
{
int n = values.Length;

for (int i = 0; i < n - 1; i++)
{
int j = Next(i, n);

if (j != i)
{
T temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
}

/// <summary>
Expand Down Expand Up @@ -231,6 +248,25 @@ public override void NextBytes(Span<byte> buffer)
buffer[i] = (byte)_parent.Next();
}
}

public override void Shuffle<T>(Span<T> values)
{
_prng.EnsureInitialized(_seed);

int n = values.Length;

for (int i = 0; i < n - 1; i++)
{
int j = Next(i, n);

if (j != i)
{
T temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ internal abstract class ImplBase

public abstract void NextBytes(Span<byte> buffer);

public abstract void Shuffle<T>(Span<T> values);

// NextUInt32/64 algorithms based on https://arxiv.org/pdf/1805.10941.pdf and https://github.com/lemire/fastrange.

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,83 @@ ref MemoryMarshal.GetReference(buffer),
_s3 = s3;
}

public override void Shuffle<T>(Span<T> values)
{
// The upper limit of the first random number generated.
// 2432902008176640000 == 20! (Largest factorial smaller than 2^64)
ulong bound = 2432902008176640000;
int nextIndex = Math.Min(20, values.Length);

for (int i = 1; i < values.Length;)
{
ulong r = NextUInt64();

// Correct r to be unbiased.
// Ensure that the result of `Math.BigMul(r, bound, out _)` is
// uniformly distributed between 0 <= result < bound without bias.
ulong rbound = r * bound;

// Look at the lower 64 bits of r * bound,
// and if there is a carryover possibility...
// (The maximum value added in subsequent processing is bound - 1,
// so if rbound <= (2^64) - bound, no carryover occurs.)
if (rbound > 0 - bound)
{
ulong sum, carry;
do
{
// Generate an additional random number t and check if it carries over
// [rhi] . [rlo] -> r * bound; upper rhi, lower rlo
// + 0 . [thi] [tlo] -> t * bound; upper thi, lower tlo
// ---------------------
// [carry. sum] [tlo] -> rhi + carry is the result
ulong t = NextUInt64();
ulong thi = Math.BigMul(t, bound, out ulong tlo);
sum = rbound + thi;
carry = sum < rbound ? 1ul : 0ul;
rbound = tlo;

// If sum == 0xff...ff, there is a possibility of a carry
// in the future, so calculate it again.
// If not, there will be no more carry,
// so add the carry and finish.
} while (sum == ~0ul);
r += carry;
}

// Do the Fisher-Yates shuffle based on r.
// For example, the result of `Math.BigMul(r, 20!, out _)` is expressed as
// (0..2) * 20!/2! + (0..3) * 20!/3! + ... + (0..20) * 20!/20!
// Imagine extracting the numbers inside the parentheses.
for (int m = i; m < nextIndex; m++)
{
int index = (int)Math.BigMul(r, (ulong)(m + 1), out r);

// Swap span[m] <-> span[index]
T temp = values[m];
values[m] = values[index];
values[index] = temp;
}

i = nextIndex;

// Calculates next bound.
// bound is (i + 1) * (i + 2) * ... * (nextIndex) < 2^64
bound = (ulong)(i + 1);
for (nextIndex = i + 1; nextIndex < values.Length; nextIndex++)
{
if (Math.BigMul(bound, (ulong)(nextIndex + 1), out var newbound) == 0)
{
bound = newbound;
}
else
{
break;
}
}
}
}

public override double NextDouble() =>
// See comment in Xoshiro256StarStarImpl.
(NextUInt64() >> 11) * (1.0 / (1ul << 53));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,83 @@ ref MemoryMarshal.GetReference(buffer),
_s3 = s3;
}

public override void Shuffle<T>(Span<T> values)
{
// The upper limit of the first random number generated.
// 2432902008176640000 == 20! (Largest factorial smaller than 2^64)
ulong bound = 2432902008176640000;
int nextIndex = Math.Min(20, values.Length);

for (int i = 1; i < values.Length;)
{
ulong r = NextUInt64();

// Correct r to be unbiased.
// Ensure that the result of `Math.BigMul(r, bound, out _)` is
// uniformly distributed between 0 <= result < bound without bias.
ulong rbound = r * bound;

// Look at the lower 64 bits of r * bound,
// and if there is a carryover possibility...
// (The maximum value added in subsequent processing is bound - 1,
// so if rbound <= (2^64) - bound, no carryover occurs.)
if (rbound > 0 - bound)
{
ulong sum, carry;
do
{
// Generate an additional random number t and check if it carries over
// [rhi] . [rlo] -> r * bound; upper rhi, lower rlo
// + 0 . [thi] [tlo] -> t * bound; upper thi, lower tlo
// ---------------------
// [carry. sum] [tlo] -> rhi + carry is the result
ulong t = NextUInt64();
ulong thi = Math.BigMul(t, bound, out ulong tlo);
sum = rbound + thi;
carry = sum < rbound ? 1ul : 0ul;
rbound = tlo;

// If sum == 0xff...ff, there is a possibility of a carry
// in the future, so calculate it again.
// If not, there will be no more carry,
// so add the carry and finish.
} while (sum == ~0ul);
r += carry;
}

// Do the Fisher-Yates shuffle based on r.
// For example, the result of `Math.BigMul(r, 20!, out _)` is expressed as
// (0..2) * 20!/2! + (0..3) * 20!/3! + ... + (0..20) * 20!/20!
// Imagine extracting the numbers inside the parentheses.
for (int m = i; m < nextIndex; m++)
{
int index = (int)Math.BigMul(r, (ulong)(m + 1), out r);

// Swap span[m] <-> span[index]
T temp = values[m];
values[m] = values[index];
values[index] = temp;
}

i = nextIndex;

// Calculates next bound.
// bound is (i + 1) * (i + 2) * ... * (nextIndex) < 2^64
bound = (ulong)(i + 1);
for (nextIndex = i + 1; nextIndex < values.Length; nextIndex++)
{
if (Math.BigMul(bound, (ulong)(nextIndex + 1), out var newbound) == 0)
{
bound = newbound;
}
else
{
break;
}
}
}
}

public override double NextDouble() =>
// As described in http://prng.di.unimi.it/:
// "A standard double (64-bit) floating-point number in IEEE floating point format has 52 bits of significand,
Expand Down
14 changes: 1 addition & 13 deletions src/libraries/System.Private.CoreLib/src/System/Random.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,19 +363,7 @@ public void Shuffle<T>(T[] values)
/// </remarks>
public void Shuffle<T>(Span<T> values)
{
int n = values.Length;

for (int i = 0; i < n - 1; i++)
{
int j = Next(i, n);

if (j != i)
{
T temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
_impl.Shuffle(values);
}

/// <summary>Returns a random floating-point number between 0.0 and 1.0.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace System.Security.Cryptography
Expand Down Expand Up @@ -288,17 +289,80 @@ public static string GetHexString(int stringLength, bool lowercase = false)
/// <typeparam name="T">The type of span.</typeparam>
public static void Shuffle<T>(Span<T> values)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes for cryptographic RNG may subject to more careful review for security requirements.

{
int n = values.Length;
// The upper limit of the first random number generated.
// 2432902008176640000 == 20! (Largest factorial smaller than 2^64)
ulong bound = 2432902008176640000;
int nextIndex = Math.Min(20, values.Length);

for (int i = 0; i < n - 1; i++)
for (int i = 1; i < values.Length;)
{
int j = GetInt32(i, n);
ulong r = 0;
RandomNumberGeneratorImplementation.FillSpan(MemoryMarshal.AsBytes(new Span<ulong>(ref r)));

// Correct r to be unbiased.
// Ensure that the result of `Math.BigMul(r, bound, out _)` is
// uniformly distributed between 0 <= result < bound without bias.
ulong rbound = r * bound;

// Look at the lower 64 bits of r * bound,
// and if there is a carryover possibility...
// (The maximum value added in subsequent processing is bound - 1,
// so if rbound <= (2^64) - bound, no carryover occurs.)
if (rbound > 0 - bound)
{
ulong sum, carry;
do
{
// Generate an additional random number t and check if it carries over
// [rhi] . [rlo] -> r * bound; upper rhi, lower rlo
// + 0 . [thi] [tlo] -> t * bound; upper thi, lower tlo
// ---------------------
// [carry. sum] [tlo] -> rhi + carry is the result
ulong t = 0;
RandomNumberGeneratorImplementation.FillSpan(MemoryMarshal.AsBytes(new Span<ulong>(ref t)));

ulong thi = Math.BigMul(t, bound, out ulong tlo);
sum = rbound + thi;
carry = sum < rbound ? 1ul : 0ul;
rbound = tlo;

// If sum == 0xff...ff, there is a possibility of a carry
// in the future, so calculate it again.
// If not, there will be no more carry,
// so add the carry and finish.
} while (sum == ~0ul);
r += carry;
}

// Do the Fisher-Yates shuffle based on r.
// For example, the result of `Math.BigMul(r, 20!, out _)` is expressed as
// (0..2) * 20!/2! + (0..3) * 20!/3! + ... + (0..20) * 20!/20!
// Imagine extracting the numbers inside the parentheses.
for (int m = i; m < nextIndex; m++)
{
int index = (int)Math.BigMul(r, (ulong)(m + 1), out r);

// Swap span[m] <-> span[index]
T temp = values[m];
values[m] = values[index];
values[index] = temp;
}

i = nextIndex;

if (i != j)
// Calculates next bound.
// bound is (i + 1) * (i + 2) * ... * (nextIndex) < 2^64
bound = (ulong)(i + 1);
for (nextIndex = i + 1; nextIndex < values.Length; nextIndex++)
{
T temp = values[i];
values[i] = values[j];
values[j] = temp;
if (Math.BigMul(bound, (ulong)(nextIndex + 1), out var newbound) == 0)
{
bound = newbound;
}
else
{
break;
}
}
}
}
Expand Down
Loading
Loading