Skip to content

Speed improvements for Maths.Abs() on integers #113651

Closed as not planned
Closed as not planned

Description

@Corniel

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;
        }
    }
}

Activity

  1. added
    tenet-performance
    on Mar 18, 2025
  2. ghost added
    needs-area-label
    on Mar 18, 2025
  3. added
    untriaged
    on Mar 18, 2025
  4. added and removed
    needs-area-label
    on Mar 18, 2025
  5. dotnet-policy-service commented on Mar 18, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-numerics
    See info in area-owners.md if you want to be subscribed.

  6. KalleOlaviNiemitalo commented on Mar 18, 2025

    @KalleOlaviNiemitalo

    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:

      int signFill = value >> 31;
      int abs = (value + signFill) ^ signFill;
    • If you replace (abs & 0x8000_0000) == 0 with abs >= 0, then the x64 JIT compiler replaces test eax, 0x80000000 and jne short L001b with just jl short L0016, using the flags that were set by xor. So the asm code becomes shorter but I don't know whether it's faster.

  7. Corniel commented on Mar 18, 2025

    @Corniel
    Author

    @KalleOlavi

    * 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:
      int signFill = value >> 31;
      int abs = (value + signFill) ^ signFill;
    
    * If you replace `(abs & 0x8000_0000) == 0` with `abs >= 0`, then the x64 JIT compiler replaces `test eax, 0x80000000` and `jne short L001b` with just `jl short L0016`, using the flags that were set by `xor`.  So the asm code becomes shorter but I don't know whether it's faster.
    

    I did not (even) check the JIT output yet. The current implementation re-assigns the value. From that perspective it should be this:

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static int Abs(int value)
    {
        value = (value + (value >>= 31)) ^ value
        
        if (value < 0 )
        {
            ThrowNegateTwosCompOverflow();
        }
        return value;
    }

    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.

  8. huoyaoyuan commented on Mar 18, 2025

    @huoyaoyuan
    Member

    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:

            [MethodImpl(MethodImplOptions.NoInlining)]
            public static int CMov(int value)
            {
                int result = value < 0 ? -value : value;
    
                if (value == int.MinValue)
                {
                    throw new ArgumentOutOfRangeException(nameof(value));
                }
    
                return result;
            }

    It produces very close result to your version if NoInlining is specified:

    Method Mean Error StdDev Ratio
    Bits 928.3 us 8.75 us 8.19 us 0.22
    Math_Abs 4,148.9 us 19.07 us 17.84 us 1.00
    CMov 921.1 us 2.28 us 2.14 us 0.22

    However with AggressiveInlining, the compiler fails to emit cmov for it, and the performance is close to existing implementation.

  9. huoyaoyuan commented on Mar 18, 2025

    @huoyaoyuan
    Member

    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.

  10. Corniel commented on Mar 18, 2025

    @Corniel
    Author

    @huoyaoyuan I fully agree that ideally Cmov should be used. With these updated implementations, I get this:

    Method Mean Error StdDev Median Ratio RatioSD
    value < 0 654.1 us 13.88 us 40.04 us 640.6 us 0.16 0.01
    value != int.MinValue 614.8 us 11.55 us 10.81 us 615.2 us 0.15 0.00
    NoInlining 1,315.7 us 25.25 us 24.80 us 1,317.2 us 0.32 0.01
    Inlining 4,165.7 us 70.56 us 66.00 us 4,147.8 us 1.02 0.03
    Math_Abs 4,073.0 us 80.35 us 104.48 us 4,035.6 us 1.00 0.04

    I do not get the result that you do, but it is also faster. So at my system, NoInlining does improve things, but the bit implementation is still two times faster. Do you have any idea why that is?

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static int LT0(int value)
    {
        value = (value + (value >>= 31)) ^ value;
    
        if (value < 0)
        {
            throw new OverflowException("Some message");
        }
        return value;
    }
    
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static int NotIntMinValue(int value)
    {
        value = (value + (value >>= 31)) ^ value;
    
        if (value == int.MinValue)
        {
            throw new OverflowException("Some message");
        }
        return value;
    }
    
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static int Current(int value)
    {
        if (value < 0)
        {
            value = -value;
            if (value < 0)
            {
                throw new OverflowException("Some message");
            }
        }
        return value;
    }
    
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int NoInlining(int value)
    {
        value = value < 0 ? -value : value;
    
        if (value == int.MinValue)
        {
            throw new OverflowException("Some message");
        }
    
        return value;
    }
    
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static int CMov(int value)
    {
        value = value < 0 ? -value : value;
    
        if (value == int.MinValue)
        {
            throw new OverflowException("Some message");
        }
    
        return value;
    }
  11. huoyaoyuan commented on Mar 18, 2025

    @huoyaoyuan
    Member

    I do not get the result that you do, but it is also faster. So at my system, NoInlining does improve things, but the bit implementation is still two times faster. Do you have any idea why that is?

    I was comparing all implementations with NoInlining specified to get rid of additional factors.

  12. Corniel commented on Mar 18, 2025

    @Corniel
    Author

    @huoyaoyuan

    Without inlining I get this:

    Method Mean Error StdDev Ratio RatioSD
    < 0 1.775 ms 0.0773 ms 0.2278 ms 0.24 0.04
    != int.MinValue 1.517 ms 0.0696 ms 0.2029 ms 0.20 0.03
    Alternative 1.745 ms 0.0609 ms 0.1797 ms 0.23 0.03
    Math.Abs 7.519 ms 0.2328 ms 0.6863 ms 1.01 0.13

    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.Sign implementation:

    Sign(int value) => unchecked(value >> 31 | (int)((uint)-value >> 31))

    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.

  13. huoyaoyuan commented on Mar 18, 2025

    @huoyaoyuan
    Member

    But doesn't that mean that the bit-wise implementation still benefits from the in-lining, where your alternative implementation does not?

    No. Every implementation should benefit from inlining. It's the JIT missing the cmov optimization after inlining.

    So having hardcore bit operations are not uncommon in System.Math.

    It's evaluated case-by-case.

  14. LWChris commented on Mar 18, 2025

    @LWChris

    Not sure what's going on for my computer, but for me, CMov with NoInlining is faster than the current implementation, but not nearly as fast as the other approaches:

    Method Inlined Mean Error StdDev Ratio
    Math_Abs Yes 3,491.4 us 8.76 us 7.76 us 1.00
    Bits Yes 552.7 us 1.76 us 1.47 us 0.16
    < 0 Yes 550.0 us 1.12 us 0.94 us 0.16
    != int.MinValue Yes 548.2 us 1.26 us 1.05 us 0.16
    CMov Yes 3,640.6 us 3.69 us 2.88 us 1.04
    Bits No 1,146.3 us 1.25 us 1.05 us 0.33
    < 0 No 948.7 us 2.47 us 2.19 us 0.27
    != int.MinValue No 1,153.7 us 3.20 us 2.99 us 0.33
    CMov No 1,156.5 us 2.04 us 1.91 us 0.33

    I'm new to BechmarkDotNet so maybe I messed something up?

  15. IDisposable commented on Mar 19, 2025

    @IDisposable
    Contributor

    Happy to float a PR for all the integral types.

  16. Corniel commented on Mar 19, 2025

    @Corniel
    Author

    @IDisposable Thanks, but I already did that myself.

  17. added
    in-pr
    on Mar 19, 2025
  18. huoyaoyuan commented on Mar 19, 2025

    @huoyaoyuan
    Member

    It hasn't been decided to go with the bit manipulation approach. Better for @dotnet/jit-contrib to speak about the cmov optimization.

  19. huoyaoyuan commented on Mar 19, 2025

    @huoyaoyuan
    Member

    Not sure what's going on for my computer, but for me, CMov with NoInlining is faster than the current implementation, but not nearly as fast as the other approaches:

    Again, it's meaningless to compare NoInlining with AggressiveInlining. The total reason for using NoInlining is to create a fair environment for evaluating the performance of cmov.

    And also, the code for cmov by @Corniel is incorrect. The MinValue test should be performed on the input value, not the result value. It will affect parallel execution of independent execution of CPU.

  20. Corniel commented on Mar 19, 2025

    @Corniel
    Author

    @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.

  21. LWChris commented on Mar 19, 2025

    @LWChris

    Not sure what's going on for my computer, but for me, CMov with NoInlining is faster than the current implementation, but not nearly as fast as the other approaches:

    It's meaningless to compare NoInlining with AggressiveInlining. The total reason for using NoInlining is to create a fair environment for evaluating the performance of cmov.

    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 my NoInlining set, which does not seem to agree with other people's NoInlining tests.

    I understand and agree that the final decision should be made based on the results of AggressiveInlining benchmarks, which cannot be done before the compiler actually emits the cmov instruction for that implementation with inlining.

  22. tannergooding commented on Mar 19, 2025

    @tannergooding
    Member

    Benchmarking cmov is difficult because if (...) 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.

  23. LWChris commented on Mar 19, 2025

    @LWChris

    The current implementation is going to be "faster" assuming we have inputs that are consistently positive or consistently negative.

    I'm not sure, but usually I put Math.Abs(i) when the nature of i is unclear; if i was "consistently positive or consistently negative", you'd use i or -i, wouldn't you?

  24. tannergooding commented on Mar 19, 2025

    @tannergooding
    Member

    consistently is not the same as always

    If it was always negative, then yes you might use -x or you might still use Abs(x) for clarity.

    But if its just consistently/mostly negative and rarely positive (or vice-versa), you must use Abs(x)

  25. tannergooding commented on Jul 9, 2025

    @tannergooding
    Member

    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.

  26. removed
    untriaged
    on Jul 9, 2025
  27. locked and limited conversation to collaborators on Aug 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Numericsin-prtenet-performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions