下面是我的测试代码,以及执行输出结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using UnityEngine; using System.Collections; public class Distance : MonoBehaviour { private Vector3 start = new Vector3(0,0,0); private Vector3 end = new Vector3(100, 100, 100); // Use this for initialization void Start () { const int total = 1000000; System.Diagnostics.Stopwatch w1 = new System.Diagnostics.Stopwatch(); w1.Start(); int i=0; float dis1 = 0f; while (i < total) { dis1 = Vector3.Distance(start, end); i++; } w1.Stop(); Debug.Log("dis1Time : " + w1.ElapsedMilliseconds); Debug.Log("dis1 : " + dis1); System.Diagnostics.Stopwatch w2 = new System.Diagnostics.Stopwatch(); w2.Start(); int z = 0; float dis2 = 0f; float dx = end.x - start.x; float dy = end.y - start.y; float dz = end.z - start.z; while (z < total) { dis2 = Mathf.Sqrt(dx * dx + dy * dy + dz * dz); z++; } w2.Stop(); Debug.Log("dis2Time : " + w2.ElapsedMilliseconds); Debug.Log("dis2 : " + dis2); System.Diagnostics.Stopwatch w3 = new System.Diagnostics.Stopwatch(); w3.Start(); int x = 0; float dis3 = 0f; while (x < total) { dis3 = Mathf.Sqrt((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y) + (end.z - start.z) * (end.z - start.z)); x++; } w3.Stop(); Debug.Log("dis3Time : " + w3.ElapsedMilliseconds); Debug.Log("dis3 : " + dis3); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
dis1Time : 23 UnityEngine.Debug:Log(Object) Distance:Start() (at Assets/Distance.cs:26) dis1 : 173.2051 UnityEngine.Debug:Log(Object) Distance:Start() (at Assets/Distance.cs:27) dis2Time : 7 UnityEngine.Debug:Log(Object) Distance:Start() (at Assets/Distance.cs:44) dis2 : 173.2051 UnityEngine.Debug:Log(Object) Distance:Start() (at Assets/Distance.cs:45) dis3Time : 9 UnityEngine.Debug:Log(Object) Distance:Start() (at Assets/Distance.cs:58) dis3 : 173.2051 UnityEngine.Debug:Log(Object) Distance:Start() (at Assets/Distance.cs:59) |
可以看出,上面的三种计算方式,Unity自己的API执行效率是最慢的,不过这个计算量比较大,如果计算量比较小的情况下,这点效率其实可以忽略,还有就是如果是自己计算,很多情况下,Y轴的数据可以不包含在计算中,这样执行效率能够提升更多。