Repository navigation
Closed as not planned
Labels
area-System.Numericsin-prThere is an active PR which will close this issue when it is mergedtenet-performancePerformance related issue
Description
Description
Out of curiosity I was playing a bit with a bit-wise implementation of getting the absolute value of an int, and stumbled upon this implementation:
public static Abs(int value) => (value + (value >>= 31)) ^ value;Obviously, this does not handle the int.MinValue case as Math.Abs(int) does. With a small adjustment you get this:
public static int Bits(int value)
{
var abs = (value + (value >>= 31)) ^ value;
return (abs & 0x8000_0000) == 0
? abs
: throw new ArgumentOutOfRangeException(nameof(value));
}Benchmark
It turns out that this is way faster. I run a benchmark (see code below), and it turns out to take only 15% of the time. Is this something Math.Abs() should take into account? (It should work for sbyte, short, long, and int128 to, obviously).
| Method | Mean | Error | StdDev | Ratio | RatioSD |
|---|---|---|---|---|---|
| Bits | 635.9 us | 10.02 us | 8.37 us | 0.15 | 0.00 |
| Math.Abs | 4,212.2 us | 82.54 us | 118.38 us | 1.00 | 0.04 |
public class Abs
{
private const int Count = 1_000_000;
private readonly int[] I = new int[Count];
private readonly int[] O = new int[Count];
public Abs()
{
var rnd = new Random(42);
for (int i = 0; i < Count; i++)
{
I[i] = rnd.Next(-8000, 8001) * rnd.Next(8000);
}
}
[Benchmark]
public void Bits()
{
for (var i = 0; i < Count; i++)
{
O[i] = Imp.Bits(I[i]);
}
}
[Benchmark(Baseline = true)]
public void Math_Abs()
{
for (var i = 0; i < I.Length; i++)
{
O[i] = Imp.Current(I[i]);
}
}
public static class Imp
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Bits(int value)
{
var abs = (value + (value >>= 31)) ^ value;
return (abs & 0x8000_0000) == 0
? abs
: throw new ArgumentOutOfRangeException(nameof(value));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Current(int value)
{
if (value < 0)
{
value = -value;
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
}
return value;
}
}
}Metadata
Metadata
Assignees
Labels
area-System.Numericsin-prThere is an active PR which will close this issue when it is mergedtenet-performancePerformance related issue
Activity
dotnet-policy-service commentedon Mar 18, 2025
Tagging subscribers to this area: @dotnet/area-system-numerics
See info in area-owners.md if you want to be subscribed.
KalleOlaviNiemitalo commentedon Mar 18, 2025
From SharpLab, it seems that:
The JIT assembly is the same if you put the sign into a separate variable rather than update
value. I'd prefer this because it's easier to understand than updating a variable in the middle of an expression:If you replace
(abs & 0x8000_0000) == 0withabs >= 0, then the x64 JIT compiler replacestest eax, 0x80000000andjne short L001bwith justjl short L0016, using the flags that were set byxor. So the asm code becomes shorter but I don't know whether it's faster.Corniel commentedon Mar 18, 2025
@KalleOlavi
I did not (even) check the JIT output yet. The current implementation re-assigns the value. From that perspective it should be this:
But my first goal was to check if there is agreement on the benchmark results, and based on that, if this code change is considered a (potential) improvement.
huoyaoyuan commentedon Mar 18, 2025
Current implementation can't utilize conditional move instructions on modern CPUs because the throw check is contained in the sign-testing branch.
Consider a slightly modified version:
It produces very close result to your version if
NoInliningis specified:However with
AggressiveInlining, the compiler fails to emitcmovfor it, and the performance is close to existing implementation.huoyaoyuan commentedon Mar 18, 2025
The expected approach should be taking the cmov approach and ensure it's properly optimized. It's much easier to read and can interact better with other optimizations. It's not uncommon to see a certain value asserted as never-negative with inlining.
Corniel commentedon Mar 18, 2025
@huoyaoyuan I fully agree that ideally
Cmovshould be used. With these updated implementations, I get this:I do not get the result that you do, but it is also faster. So at my system,
NoInliningdoes improve things, but the bit implementation is still two times faster. Do you have any idea why that is?huoyaoyuan commentedon Mar 18, 2025
I was comparing all implementations with
NoInliningspecified to get rid of additional factors.Corniel commentedon Mar 18, 2025
@huoyaoyuan
Without inlining I get this:
But doesn't that mean that the bit-wise implementation still benefits from the in-lining, where your alternative implementation does not?
I checked the
Math.Signimplementation:So having hardcore bit operations are not uncommon in
System.Math. If not needed, I agree that an easier to follow implementation prevails, but the numbers give me the impression that this is not guaranteed.huoyaoyuan commentedon Mar 18, 2025
No. Every implementation should benefit from inlining. It's the JIT missing the cmov optimization after inlining.
It's evaluated case-by-case.
LWChris commentedon Mar 18, 2025
Not sure what's going on for my computer, but for me, CMov with
NoInliningis faster than the current implementation, but not nearly as fast as the other approaches:I'm new to BechmarkDotNet so maybe I messed something up?
IDisposable commentedon Mar 19, 2025
Happy to float a PR for all the integral types.
Corniel commentedon Mar 19, 2025
@IDisposable Thanks, but I already did that myself.
huoyaoyuan commentedon Mar 19, 2025
It hasn't been decided to go with the bit manipulation approach. Better for @dotnet/jit-contrib to speak about the cmov optimization.
huoyaoyuan commentedon Mar 19, 2025
Again, it's meaningless to compare
NoInliningwithAggressiveInlining. The total reason for usingNoInliningis to create a fair environment for evaluating the performance of cmov.And also, the code for cmov by @Corniel is incorrect. The
MinValuetest should be performed on the input value, not the result value. It will affect parallel execution of independent execution of CPU.Corniel commentedon Mar 19, 2025
@huoyaoyuan I agree that the check should be done on the input. But it is done on the output in the current implementation, so I kept that the same.
LWChris commentedon Mar 19, 2025
Yes, and out of the four approaches - all fairly tested with
NoInlining- "CMov" was the slowest. And while very comparable to "Bits" and "!= int.MinValue", it was not nearly as fast as "< 0". That's what I'm saying. If "CMov" was the baseline, "< 0" ratio would be 0.82 within myNoInliningset, which does not seem to agree with other people'sNoInliningtests.I understand and agree that the final decision should be made based on the results of
AggressiveInliningbenchmarks, which cannot be done before the compiler actually emits the cmov instruction for that implementation with inlining.tannergooding commentedon Mar 19, 2025
Benchmarking
cmovis difficult becauseif (...)will often get trained.The current implementation is going to be "faster" assuming we have inputs that are consistently positive or consistently negative. The proposed implementation is going to be "faster" for truly random inputs.
LWChris commentedon Mar 19, 2025
I'm not sure, but usually I put
Math.Abs(i)when the nature ofiis unclear; ifiwas "consistently positive or consistently negative", you'd useior-i, wouldn't you?tannergooding commentedon Mar 19, 2025
consistentlyis not the same asalwaysIf it was always negative, then yes you might use
-xor you might still useAbs(x)for clarity.But if its just consistently/mostly negative and rarely positive (or vice-versa), you must use
Abs(x)tannergooding commentedon Jul 9, 2025
Closing this. The code is correct as is and we're not interested in significantly modifying it to microtune the codegen.
It would be better to have the JIT recognize the pattern and do the "optimal" thing based on PGO data.