小編給大家分享一下Unity C#中Mathf.Abs()取絕對值性能測試的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
這性能差距有點不太合理??! 看下源碼發現 很多Mathf的方法就是多封裝了一層Math里的方法 把double型轉成float型了 即便很簡單得方法也沒有重新實現
官方有點偷懶了 所以性能差距才會這么大 以后要求性能高的地方要注意 老老實實寫一遍 能提升不少性能
測試代碼:
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()源碼:
// 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部分源碼:
以上是“Unity C#中Mathf.Abs()取絕對值性能測試的示例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。