- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- Unity C#中Mathf.Abs()取絕對值性能測試的示例分析
小編給大家分享一下Unity C#中Mathf.Abs()取絕對值性能測試的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
這性能差距有點(diǎn)不太合理??! 看下源碼發(fā)現 很多Mathf的方法就是多封裝了一層Math里的方法 把double型轉成float型了 即便很簡(jiǎn)單得方法也沒(méi)有重新實(shí)現
官方有點(diǎn)偷懶了 所以性能差距才會(huì )這么大 以后要求性能高的地方要注意 老老實(shí)實(shí)寫(xiě)一遍 能提升不少性能
測試代碼:
using UnityEngine; using UnityEditor; using System.Diagnostics; /// <summary> /// 執行時(shí)間測試 /// 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); // 自己實(shí)現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部分源碼:
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站