欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于Unity C# Mathf.Abs()取絕對(duì)值性能測(cè)試詳解

 更新時(shí)間:2019年04月15日 08:35:56   作者:冰封百度  
這篇文章主要給大家介紹了關(guān)于Unity C# Mathf.Abs()取絕對(duì)值性能測(cè)試的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Unity C#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

前言

之前有人提到過取絕對(duì)值時(shí) 直接寫三目運(yùn)算符比用Mathf.Abs()效率高 沒覺得能高太多

今天測(cè)了一下 真是不測(cè)不知道 一測(cè)嚇一跳 直接寫三目運(yùn)算符比Mathf.Abs()效率高2-3倍

這性能差距有點(diǎn)不太合理??! 看下源碼發(fā)現(xiàn) 很多Mathf的方法就是多封裝了一層Math里的方法 把double型轉(zhuǎn)成float型了 即便很簡(jiǎn)單得方法也沒有重新實(shí)現(xiàn)

官方有點(diǎn)偷懶了 所以性能差距才會(huì)這么大 以后要求性能高的地方要注意 老老實(shí)實(shí)寫一遍 能提升不少性能

測(cè)試代碼:

using UnityEngine;
using UnityEditor;
using System.Diagnostics;

/// <summary>
/// 執(zhí)行時(shí)間測(cè)試
/// 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/執(zhí)行")]
 private static void Execute() {
 watch = new Stopwatch();

 // 數(shù)據(jù)
 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í)現(xiàn)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);

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

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

 // == 執(zhí)行次數(shù):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;
 }

 // 三目運(yùn)算符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部分源碼:

更高性能取絕對(duì)值方法:
http://www.dbjr.com.cn/article/159706.htm...

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論