Performance test of taking absolute value of unity C × mathf. Abs()

Posted by warren on Sat, 30 Nov 2019 18:40:50 +0100

It has been mentioned before that it's more efficient to write the binocular operator directly when taking absolute value than to use Math.Abs(). I don't think it's much more efficient
Today's test is really unexpected. I don't know that it's about 20% faster when I'm scared

This performance gap is a little bit unreasonable. Look at the source code, we find that many Mathf methods encapsulate one more layer of Math methods to convert double type to float type. Even if it is very simple, the method has not been re implemented
The official is a bit lazy, so the performance gap will be so large. In the future, we need to pay attention to the places with high performance. It can improve a lot of performance if we write it honestly

Mathf.Abs() source code:

// Returns the absolute value of /f/.
public static float Abs(float f) { return (float)Math.Abs(f); }

// Returns the absolute value of /value/.
public static int Abs(int value) { return Math.Abs(value); }

Test code:

using UnityEngine;
using UnityEditor;
using System.Diagnostics;

/// <summary>
///Execution time test
/// ZhangYu 2019-04-04
/// </summary>
public class TimeTest : MonoBehaviour {

    public int executeTimes = 1;

    private void OnValidate() {
        times = executeTimes;
    }

    ///< summary > execution times < / summary >
    private static int times = 1;
    private static Stopwatch watch = new Stopwatch();

    [MenuItem("CONTEXT/TimeTest/implement")]
    private static void Execute() {
        watch.Reset();
        watch.Start();
        float a = 0.1f;
        for (int i = 0; i < times; i++) {
            FloatAbs2(a);
        }
        watch.Stop();
        print(string.Format("Times: {0} Elaped: {1}", times, watch.Elapsed));
    }

    // Method 1: Times: 1000000 elapsed: 0.0267839 - 0.0278066
    // Mathf.Abs(a)

    // Method 2: Times: 1000000 elapsed: 0.0178621 - 0.0181184
    public static int IntAbs2(int a) {
        return (a ^ (a >> 31)) - (a >> 31);
    }

    // Method 1: Times: 1000000 elapsed: 0.0277130 - 0.0289079
    // Mathf.Abs(a)

    // Times: 1000000 Elaped: 0.0207271 - 0.0220157
    private static float FloatAbs2(float a) {
        return a < 0 ? -a : a;
    }

}

Part of the official Mathf source code:

Higher performance absolute value method:
https://blog.csdn.net/qq_1507...

Topics: C#