内容简介:之前有人提到过取绝对值时 直接写三目运算符比用Math.Abs()效率高 没觉得能高太多今天测了一下 真是不测不知道 一测吓一跳 居然快了20%左右这性能差距有点不太合理啊 看下源码发现 很多Mathf的方法就是多封装了一层Math里的方法 把double型转成float型了 即便很简单得方法也没有重新实现
之前有人提到过取绝对值时 直接写三目运算符比用Math.Abs()效率高 没觉得能高太多
今天测了一下 真是不测不知道 一测吓一跳 居然快了20%左右
这性能差距有点不太合理啊 看下源码发现 很多Mathf的方法就是多封装了一层Math里的方法 把double型转成float型了 即便很简单得方法也没有重新实现
官方有点偷懒了 所以性能差距才会这么大 以后要求性能高的地方要注意 老老实实写一遍 能提升不少性能
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); }
测试代码:
using UnityEngine; using UnityEditor; using System.Diagnostics; /// <summary> /// 执行时间测试 /// ZhangYu 2019-04-04 /// </summary> public class TimeTest : MonoBehaviour { public int executeTimes = 1; private void OnValidate() { times = executeTimes; } /// <summary> 执行次数 </summary> private static int times = 1; private static Stopwatch watch = new Stopwatch(); [MenuItem("CONTEXT/TimeTest/执行")] 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)); } // 方法1: Times: 1000000 Elaped: 0.0267839 - 0.0278066 // Mathf.Abs(a) // 方法2: Times: 1000000 Elaped: 0.0178621 - 0.0181184 public static int IntAbs2(int a) { return (a ^ (a >> 31)) - (a >> 31); } // 方法1: Times: 1000000 Elaped: 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; } }
官方Mathf部分源码:
更高性能取绝对值方法:
https://blog.csdn.net/qq_1507...以上所述就是小编给大家介绍的《Unity C# Mathf.Abs()取绝对值性能测试》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Java 解惑系列(五):绝对值小于 0 的整数存在么
- Java 解惑系列(五):绝对值小于 0 的整数存在么
- 性能优化第一课:性能指标
- 【前端性能优化】vue性能优化
- Golang 性能测试 (2) 性能分析
- 【前端性能优化】02--vue性能优化
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Don't Make Me Think
Steve Krug / New Riders Press / 18 August, 2005 / $35.00
Five years and more than 100,000 copies after it was first published, it's hard to imagine anyone working in Web design who hasn't read Steve Krug's "instant classic" on Web usability, but people are ......一起来看看 《Don't Make Me Think》 这本书的介绍吧!