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

Even faster modulo computation #406

Merged
merged 3 commits into from
Jan 22, 2020
Merged
Changes from 1 commit
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 @@ -90,21 +90,24 @@ public static int ExpandPrime(int oldSize)
}

#if BIT64
// Returns approximate reciprocal of the divisor: ceil(2**64 / divisor)
public static ulong GetFastModMultiplier(uint divisor)
=> ulong.MaxValue / divisor + 1;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint FastMod(uint value, uint divisor, ulong multiplier)
Copy link
Member

@danmoseley danmoseley Jan 22, 2020

Choose a reason for hiding this comment

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

Nit: surely this is inlined even without the attribute..

Copy link
Member

Choose a reason for hiding this comment

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

Have you verified it? This method is going to be ~20 bytes of IL. It is in the gray where the JIT may choose to not inline it.

Copy link
Member

Choose a reason for hiding this comment

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

You are exactly right .. it is 18 bytes IL, if I remove the + 1 to make 15 bytes of IL, it is then inlined.

{
// Using fastmod from Daniel Lemire https://lemire.me/blog/2019/02/08/faster-remainders-when-the-divisor-is-a-constant-beating-compilers-and-libdivide/
// We use modified Daniel Lemire's fastmod algorithm (https://github.com/dotnet/runtime/pull/406),
// which allows to avoid the long multiplication if the divisor is less than 2**31.
Debug.Assert(divisor <= int.MaxValue);

ulong lowbits = multiplier * value;
// 64bit * 64bit => 128bit isn't currently supported by Math https://github.com/dotnet/corefx/issues/41822
// otherwise we'd want this to be (uint)Math.MultiplyHigh(lowbits, divisor)
AntonLapounov marked this conversation as resolved.
Show resolved Hide resolved
uint high = (uint)((((ulong)(uint)lowbits * divisor >> 32) + (lowbits >> 32) * divisor) >> 32);
// otherwise we'd want this to be (uint)Math.BigMul(lowbits, divisor, out _)
uint highbits = (uint)((((lowbits >> 32) + 1) * divisor) >> 32);

Debug.Assert(high == value % divisor);
return high;
Debug.Assert(highbits == value % divisor);
return highbits;
}
#endif
}
Expand Down