Mathf.Floor 与 (int) 的性能比较

sfb*_*bea 4 c# int performance unity-game-engine

当我想知道哪个更快时,我正在创建和翻译一些算法。

A)(int)float

或者

b)Mathf.FloorToInt(float)

提前致谢。

编辑:如果有比这两种方法更快的方法,那也会有帮助。

Pro*_*mer 5

像我提到的那样用秒表进行测试。这个答案在这里是因为我相信你的答案的结果是错误的。

下面是一个使用循环的简单性能测试脚本,因为您的算法涉及许多循环:

void Start()
{

    int iterations = 10000000;

    //TEST 1
    Stopwatch stopwatch1 = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        int test1 = (int)0.5f;
    }
    stopwatch1.Stop();

    //TEST 2
    Stopwatch stopwatch2 = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        int test2 = Mathf.FloorToInt(0.5f);
    }
    stopwatch2.Stop();

    //SHOW RESULT
    WriteLog(String.Format("(int)float: {0}", stopwatch1.ElapsedMilliseconds));
    WriteLog(String.Format("Mathf.FloorToInt: {0}", stopwatch2.ElapsedMilliseconds));
}

void WriteLog(string log)
{
    UnityEngine.Debug.Log(log);
}
Run Code Online (Sandbox Code Playgroud)

输出:

(整数)浮点数:73

Mathf.FloorToInt:521

(int)float显然比 更快Mathf.FloorToInt。对于这样的事情,用编辑器统计中的FPS来做出判断确实很糟糕。您用 进行测试Stopwatch。编写着色器代码时应使用 FPS。