Unity C# Mathf.Abs()取絕對值性能測試

以前有人提到過取絕對值時 直接寫三目運算符比用Mathf.Abs()效率高 沒以爲能高太多
今天測了一下 真是不測不知道 一測嚇一跳 直接寫三目運算符比Mathf.Abs()效率高2-3倍性能

這性能差距有點不太合理啊! 看下源碼發現 不少Mathf的方法就是多封裝了一層Math裏的方法 把double型轉成float型了 即使很簡單得方法也沒有從新實現
官方有點偷懶了 因此性能差距纔會這麼大 之後要求性能高的地方要注意 老老實實寫一遍 能提高很多性能測試

Abs效率對比

測試代碼:spa

using UnityEngine;
using UnityEditor;
using System.Diagnostics;

/// <summary>
/// 執行時間測試
/// ZhangYu 2019-04-04
/// </summary>
public class TimeTest : MonoBehaviour {

    public int executeTimes = 1;
    private static Stopwatch watch;

    private void OnValidate() {
        times = executeTimes;
    }

    private static int times = 1;
    [MenuItem("CONTEXT/TimeTest/執行")]
    private static void Execute() {
        watch = new Stopwatch();

        // 數據
        float a = 1;

        // Mathf.Abs
        watch.Reset();
        watch.Start();
        for (int i = 0; i < times; i++) {
            a = Mathf.Abs(a);
        }
        watch.Stop();
        string msgMathfAbs = string.Format("Mathf.Abs: {0}s", watch.Elapsed);

        // 本身實現Abs
        watch.Reset();
        watch.Start();
        for (int i = 0; i < times; i++) {
            a = MyAbs(a);
        }
        watch.Stop();
        string msgMyAbs = string.Format("自定義Abs: {0}s", watch.Elapsed);

        // 三目運算符Abs
        watch.Reset();
        watch.Start();
        for (int i = 0; i < times; i++) {
            a = a < 0 ? -a : a;
        }
        watch.Stop();
        string msg3Abs = string.Format("三目運算符Abs: {0}s", watch.Elapsed);

        print(msgMathfAbs);
        print(msgMyAbs);
        print(msg3Abs);
    }

    // == 執行次數:10000000

    // Mathf.Abs
    // (1)0.2803558s
    // (2)0.2837749s
    // (3)0.2831089s
    // (4)0.2829929s
    // (5)0.2839846s

    // 自定義Abs
    // (1)0.2162217s
    // (2)0.2103635s
    // (3)0.2103390s
    // (4)0.2092863s
    // (5)0.2097648s
    private static float MyAbs(float a) {
        return a < 0 ? -a : a;
    }

    // 三目運算符Abs
    // (1)0.0893028s
    // (2)0.1000181s
    // (3)0.1017959s
    // (4)0.1001749s
    // (5)0.1005737s

}

Mathf.Abs()源碼:.net

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

官方Mathf部分源碼:
Mathf部分源碼1
Mathf部分源碼2pwa

更高性能取絕對值方法:
https://blog.csdn.net/qq_1507...code

相關文章
相關標籤/搜索