「毎日Unity」の技術ブログ

開発で役立つ情報を発信する

【UnityC#】Math.Pow(i, 3)、Mathf.Pow(i, 3)、i * i * iの速度比較

Math.Pow(i, 3)、Mathf.Pow(i, 3)、i * i * iの速度比較をしたので結果を残しておきます。

[ 環境 ]

Unity 2021.2.19.f1

[ 比較結果 ]

Math.Pow(i, 3) 26 ms
Mathf.Pow(i, 3) 55 ms
i * i * i 0 ms
PowInt(i, 3) 3 ms

[ スクリプト ]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class PerformanceComparison : MonoBehaviour
{
    void Start()
    {
        System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();

        int Count = 1000000;

        //Math.Pow(i, 3)

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            int Temporary = (int)Math.Pow(i, 3);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //Mathf.Pow(i, 3)

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            int Temporary = (int)Mathf.Pow(i, 3);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //i * i * i

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            int Temporary = i * i * i;
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //PowInt(i, 3)

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            int Temporary = PowInt(i, 3);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);
    }

    int PowInt(int A, int B)
    {
        if(B == 0)
        {
            return 1;
        }

        int Result = 1;

        for(int i = 0; i < B; i++)
        {
            Result *= A;
        }

        return Result;
    }
}