Optimization of modulo 7 in `DateTime.DayOfWeek`
Description
In Lightning Talk: Saturday Is Coming Faster - Part 1 and Lightning Talk: Saturday Is Coming Faster -P art 2 @cassioneri presents a way to optimize % 7 for C++'s weekday::weekday{year_month_day} function.
The same micro-optimization seems to be applicable for C#'s DateTime.DayOfWeek, DateOnly.DayOfWeek and possibly other places in Calendar.cs and ISOWeek.cs using % 7.
In short: For the range of "days since epoch" between DateTime.MinValue and DateTime.MaxValue we can replace % 7 with this method.
private static uint FastMod7(uint n)
{
Debug.Assert(n < 178_956_973);
return 613_566_757 * n >> 29;
}
If we implement this fast path in DayOfWeek2, we can similarly to the talk, proof this works by simply enumerating all days between DateTime.MinValue and DateTime.MaxValue.
public DayOfWeek DayOfWeek2 => (DayOfWeek)FastMod7((uint)(UTicks / TimeSpan.TicksPerDay) + 1);
private static uint FastMod7(uint n)
{
Debug.Assert(n < 178_956_973);
return 613_566_757 * n >> 29;
}
for (var ticks = DateTime.MinValue.Ticks; ticks <= DateTime.MaxValue.Ticks; ticks += TimeSpan.TicksPerDay)
{
var d = new MyDateTime(ticks);
Debug.Assert(d.DayOfWeek == d.DayOfWeek2);
}
I tried micro benchmarking this and it shows a 5% improvement and a 14 B code size reduction.
BenchmarkDotNet v0.14.1-nightly.20250503.223, Windows 11 (10.0.26100.3775)
Unknown processor
.NET SDK 10.0.100-preview.3.25201.16
[Host] : .NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
DefaultJob : .NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
| Method | Mean | Error | StdDev | Ratio | RatioSD | Code Size |
|---|---|---|---|---|---|---|
| DayOfWeek | 0.2111 ns | 0.0015 ns | 0.0013 ns | 1.00 | 0.01 | 63 B |
| DayOfWeek2 | 0.2010 ns | 0.0039 ns | 0.0035 ns | 0.95 | 0.02 | 49 B |
asm
.NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
; WeekDayBenchmark0.DayOfWeek()
mov rdx,[rcx+8]
mov rax,3FFFFFFFFFFFFFFF
and rdx,rax
mov rcx,28B8FFC778816079
mov rax,rdx
mul rcx
shr rdx,25
lea ecx,[rdx+1]
mov rdx,2492492492492493
mov eax,ecx
mul rdx
imul eax,edx,7
sub ecx,eax
mov eax,ecx
ret
; Total bytes of code 63
.NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
; WeekDayBenchmark0.DayOfWeek2()
mov rdx,[rcx+8]
mov rax,3FFFFFFFFFFFFFFF
and rdx,rax
mov rcx,28B8FFC778816079
mov rax,rdx
mul rcx
shr rdx,25
inc edx
imul eax,edx,24924925
shr eax,1D
ret
; Total bytes of code 49
Benchmark code
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Diagnostics;
using System;
BenchmarkRunner.Run<WeekDayBenchmark>();
[DisassemblyDiagnoser]
public class WeekDayBenchmark
{
public MyDateTime MyDateTime0 { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
MyDateTime0 = new MyDateTime(DateTime.MaxValue.Ticks);
}
[Benchmark(Baseline = true)]
public DayOfWeek DayOfWeek() => MyDateTime0.DayOfWeek;
[Benchmark]
public DayOfWeek DayOfWeek2() => MyDateTime0.DayOfWeek2;
}
public readonly partial struct MyDateTime
{
private const ulong TicksMask = 0x3FFFFFFFFFFFFFFF;
internal readonly ulong _dateData;
public MyDateTime(long ticks)
{
_dateData = (ulong)ticks;
}
private ulong UTicks => _dateData & TicksMask;
public DayOfWeek DayOfWeek => (DayOfWeek)(((uint)(UTicks / TimeSpan.TicksPerDay) + 1) % 7);
public DayOfWeek DayOfWeek2 => (DayOfWeek)FastMod7((uint)(UTicks / TimeSpan.TicksPerDay) + 1);
private static uint FastMod7(uint n)
{
Debug.Assert(n < 178_956_973);
return 613_566_757 * n >> 29;
}
}
Is this something that would be worth pursuing in the BCL or is it either not worth the complexity, should be handled by the JIT or something else?
@jnyrup thanks for pointing at that. Are you interested in submitting a PR? doing quick search, here are the places can be updated.
System.Private.CoreLib\src\System\DateOnly.cs: public DayOfWeek DayOfWeek => (DayOfWeek)((_dayNumber + 1) % 7);
System.Private.CoreLib\src\System\DateTime.cs: public DayOfWeek DayOfWeek => (DayOfWeek)(((uint)(UTicks / TimeSpan.TicksPerDay) + 1) % 7);
System.Private.CoreLib\src\System\Globalization\Calendar.cs: int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
System.Private.CoreLib\src\System\Globalization\Calendar.cs: int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
System.Private.CoreLib\src\System\Globalization\Calendar.cs: dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
System.Private.CoreLib\src\System\Globalization\Calendar.cs: offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
System.Private.CoreLib\src\System\Globalization\Calendar.cs: int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
System.Private.CoreLib\src\System\Globalization\Calendar.cs: int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
System.Private.CoreLib\src\System\Globalization\Calendar.cs: int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
System.Private.CoreLib\src\System\Globalization\Calendar.cs: int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
System.Private.CoreLib\src\System\Globalization\ISOWeek.cs: return (y + (y / 4) - cent + cent / 4) % 7;
This likely isn't something that can be easily handled by the JIT due to the required range knowledge.
However, it's notably also only saving around 2 cycles (changing out a 3+1 cycle imul+sub for a 1+1 cycle shr+inc), for code that is more magic and less understandable.
The benchmark notably also gave more standard deviation and couldn't accurately measure the difference. It's reporting both as take 1 cycle on a 5GHz computer, so you likely need to modify the benchmark code to be more comprehensive and such that it takes considerably more time than the accuracy of the underlying hardware timer (you need to be spending at least 100-300ns per iteration for realistic measurements, as that is roughly what the underlying high performance counter API for the OS will return).
A more comprehensive benchmark should give a better measurement of the differences, but there's still the consideration of how that can impact maintainability of the code long term for something that's saving less cycles than a branch mispredict or L1 cache (non-missed) access and is extremely unlikely to be the bottleneck in a real app.
-- CC. @EgorBo, @jkotas since I think this touches a bit around the realm of "unsafe" code. It's not memory unsafe, but it is an optimization that relies on certain invariants in the code for a very minor perf increase
We have other existing places in DateTime code that depend on similar tricks, e.g.: https://github.com/dotnet/runtime/blob/86949c2fc8866bb56d320c8f12d501f6034336d7/src/libraries/System.Private.CoreLib/src/System/DateTime.cs#L1355-L1374
I do not see a problem with it as long as long we have sufficient test coverage. These tricks do not invalidate type or memory safety that the unsafe code is concerned with.
@tannergooding :
This likely isn't something that can be easily handled by the JIT due to the required range knowledge.
You're right that the exact optimisation shown in my talk doesn't work for all uint values so the JIT can't use it as it is. However, as I mention therein, we can increase the range of applicability by using a similar constant with more bits. For 64-bits, that is, using the ulong constant ceil(2^64 / 7), the optimisation works for all uint values. Indeed, here is an exhaustive test:
https://godbolt.org/z/oEMrxKfY5
(It takes just a few seconds to run.) I could calculate the sharp upper bound for the range of validity but I'm a bit lazy right now 😬. It certainly doesn't cover the whole range of ulong values.
However, it's notably also only saving around 2 cycles (changing out a 3+1 cycle imul+sub for a 1+1 cycle shr+inc),
I disagree that we're replacing imul + sub with shr + inc. As you can see in the same link above, the instructions to get n % 7 are:
mov rdx, 0x2492492492492493
mov eax, edi
mul rdx:rax, rdx
imul eax, edx, 7
sub edi, eax
mov eax, edi
whereas for the optimised version they are:
mov eax, edi
mov rcx, 0x2492492492492493
imul rax, rcx
shr rax, 61
Notice that we save one mul amongst other instructions. I hope this helps.
I disagree that we're replacing imul + sub with shr + inc. As you can see in the same link above, the instructions to get n % 7 are:
Register to register moves are not fixed, they are dependent on inlining, surrounding code, and other factors. They are also zero-cost and handled by the register renamer on most CPUs from the past 20ish plus years
Immediate to register moves are likewise optimized and often elided by the CPU
The instructions here with real cost are mul, Imul, sub, and shr; which comprise the difference between the two. The example just above is for 64-bit and so the codegen is slightly different from 32-bit
A more comprehensive benchmark is needed, at minimum, because the numbers given in the original post aren’t accurate. They cannot be accurate because they are showing less than a cycle for the entire operation and less than a cycle of difference between them.
Noting that inaccurate measurements are not your fault here, it’s a known issue I’ve got tracked against BDN as https://github.com/dotnet/BenchmarkDotNet/issues/1802
This has to do both with how it tries to measure empty method overhead and due to general imprecision introduced by measuring very small methods, which leads to inherent noise.
You really need to have larger test cases for accurate measurement of the relative change involved
@tannergooding I agree (almost 100%) with you on the mov instructions. My main point is that we save one mul (which you didn't mention) and, contrarily to your statement, there's no inc in the diff.
I also agree that better benchmarks are needed. (Note that I didn't write them.)
The inc exists in the full DayOfWeek2 sample, which is relevant. We do not optimize based solely on the improvement to a leaf method, we optimize based on the end to end real world usage as it impacts public APis that devs will consume
32x32=32 mul is 3 cycles. 32x32=64 mul is 4 cycles. 64x64=64 mul is 3-4 cycles on modern CPUs but on slightly older it is upwards of 10 cycles. 64x64=128 is similar. 64-bit mul also tends to be port restricted
Mul is much cheaper than divide, which is why most compilers optimize to these patterns. But most do not do the kind of transform being suggested here because the range restriction is required for it to be more optimal and even then it’s only 1-2 cycles faster
If there is a benchmark showing the additional complexity is worth the 1-2 cycle difference, then it’s worth further discussion on whether or not we want to take it
Thanks for all the input.
Here's an updated benchmark where I'm looping over DayOfWeek 10'000 times.
BenchmarkDotNet v0.14.1-nightly.20250503.223, Windows 11 (10.0.26100.3775)
Unknown processor
.NET SDK 10.0.100-preview.3.25201.16
[Host] : .NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
DefaultJob : .NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
| Method | Mean | Error | StdDev | Ratio | Code Size |
|---|---|---|---|---|---|
| DayOfWeek | 0.9915 ns | 0.0017 ns | 0.0016 ns | 1.00 | 87 B |
| DayOfWeek2 | 0.6833 ns | 0.0031 ns | 0.0029 ns | 0.69 | 75 B |
// * Detailed results *
WeekDayBenchmark.DayOfWeek: DefaultJob
Runtime = .NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI; GC = Concurrent Workstation
Mean = 0.992 ns, StdErr = 0.000 ns (0.04%), N = 15, StdDev = 0.002 ns
Min = 0.989 ns, Q1 = 0.990 ns, Median = 0.991 ns, Q3 = 0.992 ns, Max = 0.995 ns
IQR = 0.002 ns, LowerFence = 0.987 ns, UpperFence = 0.996 ns
ConfidenceInterval = [0.990 ns; 0.993 ns] (CI 99.9%), Margin = 0.002 ns (0.18% of Mean)
Skewness = 0.55, Kurtosis = 2.55, MValue = 2
-------------------- Histogram --------------------
[0.988 ns ; 0.996 ns) | @@@@@@@@@@@@@@@
---------------------------------------------------
WeekDayBenchmark.DayOfWeek2: DefaultJob
Runtime = .NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI; GC = Concurrent Workstation
Mean = 0.683 ns, StdErr = 0.001 ns (0.11%), N = 15, StdDev = 0.003 ns
Min = 0.679 ns, Q1 = 0.681 ns, Median = 0.683 ns, Q3 = 0.685 ns, Max = 0.690 ns
IQR = 0.004 ns, LowerFence = 0.675 ns, UpperFence = 0.691 ns
ConfidenceInterval = [0.680 ns; 0.686 ns] (CI 99.9%), Margin = 0.003 ns (0.45% of Mean)
Skewness = 0.52, Kurtosis = 2.35, MValue = 2
-------------------- Histogram --------------------
[0.677 ns ; 0.691 ns) | @@@@@@@@@@@@@@@
---------------------------------------------------
asm
.NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
; WeekDayBenchmark.DayOfWeek()
xor r8d,r8d
mov rcx,[rcx+8]
mov r10d,2710
M00_L00:
mov rdx,rcx
mov rax,3FFFFFFFFFFFFFFF
and rdx,rax
mov r9,28B8FFC778816079
mov rax,rdx
mul r9
shr rdx,25
lea r9d,[rdx+1]
mov rdx,2492492492492493
mov eax,r9d
mul rdx
imul eax,edx,7
sub r9d,eax
add r8d,r9d
dec r10d
jne short M00_L00
mov eax,r8d
ret
; Total bytes of code 87
.NET 10.0.0 (10.0.25.17105), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
; WeekDayBenchmark.DayOfWeek2()
xor r8d,r8d
mov rcx,[rcx+8]
mov r10d,2710
nop dword ptr [rax]
M00_L00:
mov rdx,rcx
mov rax,3FFFFFFFFFFFFFFF
and rdx,rax
mov r9,28B8FFC778816079
mov rax,rdx
mul r9
shr rdx,25
inc edx
imul eax,edx,24924925
shr eax,1D
add r8d,eax
dec r10d
jne short M00_L00
mov eax,r8d
ret
; Total bytes of code 75
Benchmark code
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Diagnostics;
using System;
BenchmarkRunner.Run<WeekDayBenchmark>();
[ReturnValueValidator]
[DisassemblyDiagnoser]
public class WeekDayBenchmark
{
public MyDateTime Value { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
Value = new MyDateTime(DateTime.MaxValue.Ticks);
}
const int OperationsPerInvoke = 10_000;
[Benchmark(Baseline = true, OperationsPerInvoke = OperationsPerInvoke)]
public int DayOfWeek()
{
int d = default;
for (int i = 0; i < OperationsPerInvoke; i++)
{
d += (int)Value.DayOfWeek;
}
return d;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public int DayOfWeek2()
{
int d = default;
for (int i = 0; i < OperationsPerInvoke; i++)
{
d += (int)Value.DayOfWeek2;
}
return d;
}
}
public readonly partial struct MyDateTime
{
private const ulong TicksMask = 0x3FFFFFFFFFFFFFFF;
internal readonly ulong _dateData;
public MyDateTime(long ticks)
{
_dateData = (ulong)ticks;
}
private ulong UTicks => _dateData & TicksMask;
public DayOfWeek DayOfWeek => (DayOfWeek)(((uint)(UTicks / TimeSpan.TicksPerDay) + 1) % 7);
public DayOfWeek DayOfWeek2 => (DayOfWeek)FastMod7((uint)(UTicks / TimeSpan.TicksPerDay) + 1);
private static uint FastMod7(uint n)
{
Debug.Assert(n < 178_956_973);
return 613_566_757 * n >> 29;
}
}
@jnyrup Wonderful results. IMHO, 31% gain in performance isn't bad at all. Also, thank you for your interest in my work.
@tannergooding Yes, you're right that the inc doesn't exist in current code and is a novelty of the proposed change.
This instruction comes from the addition to 1 in DayOfWeek2. However, this addition is also present in DayOfWeek:
public DayOfWeek DayOfWeek2 => (DayOfWeek)FastMod7((uint)(UTicks / TimeSpan.TicksPerDay) + 1);
// v ^
public DayOfWeek DayOfWeek => (DayOfWeek)(((uint)(UTicks / TimeSpan.TicksPerDay) + 1) % 7);
Although the inc is not in the assembly of DayOfWeek, the addition did not disappear from there. The line lea r9d,[rdx+1] serves to the exact same purpose. Therefore, instead of saying this:
changing out a 3+1 cycle imul+sub for a 1+1 cycle shr+inc
It would be more correct to say
changing out a (some number) cycle imul+sub+lea for a (some number) cycle shr+inc
But most do not do the kind of transform being suggested here because the range restriction is required for it to be more optimal
I previously showed (here again: https://godbolt.org/z/oEMrxKfY5) a function fast_mod7(uint n) that returns n % 7 for ALL possible values of n. Therefore, there's no range restriction and it's not true that most compilers don't use this algorithm because it has a restriction. (It has not!)
I believe that a more plausible explanation why this algorithm is not implemented by compilers is that compiler writers don't know about it. Similarly, I believe, most compiler writers don't know about a certain algorithm for divisibility checks. The exceptions are GCC and LLVM which, circa 2019, moved away from the algorithm that others still use. They use a beautiful algorithm based on the truncated 2-adic expansion of 1 / C (where C is a constant divisor). Yes, more magic numbers! Here is an example: https://godbolt.org/z/143fh3Kf7. Compare newer versions of GCC and Clang with older ones and msvc. (C# JIT compiler is similar to msvc in that perspective.)
Although I think that @jnyrup did a great job here, ideally, compilers writers would use the algorithm in fast_mod7(uint n) to get n % 7 . This would benefit anyone who writes n % 7 (when n is uint) and DayOfWeek could be left just as it is. This algorithm, by the way, can be generalised for any divisor that is a Mersenne number (3, 7, 15, ...).
@jnyrup thanks!
This matches (roughly) what I see locally on my x64 Desktop: Ryzen 7950X (which averaged 5.2 GHz for the duration of the benchmark):
| Method | Mean | Error | StdDev | Ratio | Code Size |
|---|---|---|---|---|---|
| DayOfWeek | 0.9138 ns | 0.0166 ns | 0.0204 ns | 1.00 | 87 B |
| DayOfWeek2 | 0.6291 ns | 0.0055 ns | 0.0052 ns | 0.69 | 75 B |
These numbers are for a x64 Server: Xeon 8370C (averaged 3.4 GHz):
| Method | Mean | Error | StdDev | Ratio | Code Size |
|---|---|---|---|---|---|
| DayOfWeek | 1.219 ns | 0.0082 ns | 0.0077 ns | 1.00 | 87 B |
| DayOfWeek2 | 1.038 ns | 0.0021 ns | 0.0019 ns | 0.85 | 75 B |
These numbers are for a x64 Laptop: Core i9-11900H (averaged 4.2 GHz):
| Method | Mean | Error | StdDev | Ratio | Code Size |
|---|---|---|---|---|---|
| DayOfWeek | 0.9363 ns | 0.0186 ns | 0.0273 ns | 1.00 | 87 B |
| DayOfWeek2 | 0.7741 ns | 0.0151 ns | 0.0141 ns | 0.83 | 75 B |
These numbers are for a Arm64 DevBox: Snapdragon Compute (averaged 2.9 GHz):
| Method | Mean | Error | StdDev | Ratio |
|---|---|---|---|---|
| DayOfWeek | 2.381 ns | 0.0048 ns | 0.0045 ns | 1.00 |
| DayOfWeek2 | 1.403 ns | 0.0016 ns | 0.0013 ns | 0.59 |
In all cases, this represents about 0.6-2.8 cycles (with the Arm64 dev box being the biggest and the Intel x64 Server being the least) of difference on average
My personal opinion is that it is not worth chasing after these types of 1-3 cycle improvements when the cost is making the code less readable/maintainble, particularly not in methods that are unlikely to be the hot spot for an application. This is 15-40%, but not all percents are created equal. Saving 40% on something taking 1-2 nanoseconds means nothing in contrast to a a branch mispredict taking 4-10 nanoseconds, a cache miss taking 10 nanoseconds, a network request taking 1-200 milliseconds, etc. In this case, you'd need approx. 666.7 million invocations to save 1 second of compute, 10.7 million invocations to save 16ms (1/60th of a second), and 13 invocations to save the cost of 1 branch mispredict on a modern machine.
The likelyhood that DayOfWeek is being used to this degree, is a bottleneck to your application, and is the thing that a user would need to optimize to hit any performance goals is likely very slim. This type of savings is almost certainly going to be lost in the general "noise" or "variance" that your system has, even just due to the CPU speed fluctuating due to power management and maintaining thermal temperatures.
However, I'd defer to @tarekgh on if it's something they'd like to take for DateTime and to drive forward.
This is 15-40%, but not all percents are created equal. Saving 40% on something taking 1-2 nanoseconds means nothing in contrast to a ...
That is to say. While this microbenchmark may be 30%, in a real world application this is likely to trend towards 0%, as it is not likely to be the hot spot and show up on any real world profile.
If there are real world workloads that this would impact, then having them presented would be beneficial and can help ensure the right decision is made.
Thanks all for the feedback and detailed analysis.
While I agree that the performance gained in these scenarios isn't significant, I believe introducing a helper method like FastMod7, along with a detailed comment explaining its purpose, would improve code readability. I don't anticipate this part of the code will need further changes (similar to the DateTime other optimizations), so I’d be fine with someone submitting a PR if they're interested.
The hex of the magic number 613_566_757 in this issue is 0x24924925. And I found this magic hex there by accident: https://github.com/dotnet/runtime/blob/beb14c143947346cf9c09ca056a0cee7fcc72108/src/coreclr/jit/utils.cpp
I don't know what it means.
@skyoxZ I explained the algorithm and, in particular, the magic number in my talks. Links at the very top of the original post.
//------------------------------------------------------------------------
// GetUnsignedMagic: Generates a magic number and shift amount for the magic
// number unsigned division optimization.
//
// Arguments:
// d - The divisor
// add - Pointer to a flag indicating the kind of code to generate
// shift - Pointer to the shift value to be returned
//
// Returns:
// The magic number.
//
// Notes:
// This code is adapted from _The_PowerPC_Compiler_Writer's_Guide_, pages 57-58.
// The paper is based on "Division by invariant integers using multiplication"
// by Torbjorn Granlund and Peter L. Montgomery in PLDI 94
It's written in utils.cpp.
Btw, is creation of a static FastModHelper viable?
Something like
static class FastModHelper
{
public static int FastMod3(int n);
public static long FastMod3(long n);
/* … */
public static int FastMod12(int n);
public static long FastMod12(long n);
}
@quixoticaxis shouldn’t this optimization be automatically applied by the jitter?
@quixoticaxis shouldn’t this optimization be automatically applied by the jitter?
Idk, but I doubt it: jit would need to prove range of the argument. Also see this comment.
@quixoticaxis
Idk, but I doubt it: jit would need to prove range of the argument.
As I said before, this is not true. The JIT doesn't need to check the range, it suffices to check the input type: if it's uint (not ulong), then it can use this algorithm:
https://godbolt.org/z/a69aPE4xz
This link compares the result of the proposed algorithm against built-in n % 7 for ALL uint values. They all give the same result. Please open the link and tell me if I'm wrong.
Idk, but I doubt it: jit would need to prove range of the argument.
As I said before, this is not true.
Given that the question was addressed at me personally for some reason, I assumed the question was about the signed helper above.