UnityでProfiler.BeginSampleとProfiler.EndSampleで関数をプロファイリングをするときにreturnがたくさんある場合、EndSampleを各returnの前に書かないといけなくてめんどくさい。
float Test(int condition) { Profiler.BeginSample("test"); if (condition == 1) { float a = 0.0f; for (int i = 0; i < 100000; i++) { a += Mathf.Cos(i); } Profiler.EndSample(); return a; } else if (condition == 2) { float b = 0.0f; for (int i = 0; i < 100000; i++) { b += Mathf.Sin(i); } Profiler.EndSample(); return b; } return 0.0f; Profiler.EndSample(); }
なのでusingスコープでプロファイリングできるようにするためにIDisposableを継承した構造体を作る。
関数の中でusingのスコープを作って中に計測したいコードを書く。これならどのタイミングでreturnされても計測できる。
float Test2(int condition) { using (var scope = new ProfilerScope("test2")) { if (condition == 1) { float a = 0.0f; for (int i = 0; i < 100000; i++) { a += Mathf.Cos(i); } return a; } else if (condition == 2) { float b = 0.0f; for (int i = 0; i < 100000; i++) { b += Mathf.Sin(i); } return b; } return 0.0f; } }
広告
コメントを残す