0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

(Unity)パフォーマンスを高めようとした結果、逆にパフォーマンスが悪くなった...

0
Posted at

はじめに

皆さんMathfの機能を使用されたことはありますでしょうか。こちらはUnity独自の数学関数などがまとめられた構造体ですが、今回はその機能の1つであるMathf.Powに対してのお話です。

【今回伝えたい主な内容】

  • 処理時間と引き換えにGCAllocが発生する
  • ネイティブコードで自作するのもありだが、今回の場合そこまでするほど効率が上がっているわけではない
  • 結論Mathf.Powを使うべき

【もくじ】

  • Mathf.Powについて
    • 自作のべき乗を返す関数を作成してパフォーマンス上げたいな~
  • 実装例
  • パフォーマンスチェック

【Mathf.Powについて】

Q. Mathf.Powとは
A. 第一引数の値を第二引数の値でべき乗した値を返す関数

ただこれだけの機能にはなりますが、個人的にまだまだ改善の余地があると考えました。

理由

  • Mathf.Pow(x, y)は汎用的な関数だから
    • x, y が整数、浮動小数点なども対応している関係で複雑な計算を行っている
    • マネージドコードからネイティブコードで実装された関数を呼び出している関係でわずかではあるがオーバーヘッドが発生する

上記理由から、floatやint型限定のPow関数を誰でも使いやすい形で使えるようにできればいいなと思い実装しようと考えました。

【実装例】

public static float Pow(this float value, int num)
    {
        if (num < 0)
        {
            value = 1f / value;
            num = -num;
        }
        
        var result = 1f;
        while (num > 0)
        {
            // 指数が奇数の場合は、現在の値を結果に掛ける
            if ((num & 1) == 1)
            {
                result *= value;
            }
            value *= value;
            num >>= 1;
        }
        return result;
    }

バイナリ法を用いて、高速でべき乗を求めるようにしています。

【パフォーマンスチェック】

void Start()
{
    var value = 2.0f;
    
    Profiler.BeginSample("This is Mathf example");
    var MathfTest = Mathf.Pow(value, 11);
    Profiler.EndSample();
    
    Profiler.BeginSample("This is original example");
    float originalTest = value.Pow(11);
    Profiler.EndSample();
}

試しに2.0を11乗した場合です。
計算速度は上がっていますが、GCAllocの上昇量を考慮すると正直今まで通りMathf.Powでいいかな...

スクリーンショット 2025-09-14 014606.png

【原因】

  • Boxingが原因だと思われる

なので、関数を挟まずに直接以下のように実装するとMathf.Powよりもパフォーマンスは高い

void Start()
    {
        var value = 2.0f;
        
        Profiler.BeginSample("This is Mathf example");
        var MathfTest = Mathf.Pow(value, 11);
        Profiler.EndSample();
        
        Profiler.BeginSample("This is original example");
        float originalTest = value * value * value * value * value * value * value * value * value * value * value;
        Profiler.EndSample();
    }

スクリーンショット 2025-09-14 015058.png

おわりに

変にパフォーマンスの知識などを身につけてしまったが故にパフォーマンスを悪くするところでしたね。これはいい教訓になりましたのでまだまだ精進していきます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?