Optimization principal 4: Use performance data to drive design and coding decisions.
The Unity 5 performance profiler is great, but there may be times where we wish to have completed control over the code we are running and how it displays or logs data. In this recipe, we explore how to use a freely available script for DIY performance profiling. While it's not quite as fancy as the graphical and detailed profiling of the performance profiler from Unity, it still provides low-level data about the time required for each frame by named parts of scripts, which is sufficient for making code design decisions to improve game performance.
For this recipe, we have provided C# script Profile.cs
in the 1362_11_14
folder. This is the DIY profiling script from Michael Garforth, kindly published under Creative Commons on the Unify Wiki at http://wiki.unity3d.com/index.php/Profiler.
To record processing requirements using Do-It-Yourself code profiling, follow these steps:
Profile.cs
script.DIYProfiling
to the Main Camera:using UnityEngine; using System.Collections; public class DIYProfiling : MonoBehaviour { public int outerLoopIterations = 20; public int innerLoopMaxIterations = 100; void Update(){ string profileName = "MATT_calculations"; Profile.StartProfile(profileName); for (int i = 0; i < outerLoopIterations; i++){ int innerLoopIterations = Random.Range(2,innerLoopMaxIterations); for (int j = 0; j < innerLoopIterations; j++){ float n = Random.Range(-1000f, 1000f); } } Profile.EndProfile(profileName); } private void OnApplicationQuit() { Profile.PrintResults(); } }
As you can see, the script is almost identical to that used with the Unity profiling in the previous recipe. Rather than calling the Unity Profiler, we call static (class) methods of Michael Garforth's Profile
class.
We call Profile
class methods StartProfile(…)
and EndProfile(…)
with the string name for what is to be analyzed (in this example, MATT_calculations
).
Finally, the OnApplicationQuit()
method is executed when the game is terminated, calling the PrintResuls()
method of the Profile
class, which prints to the console the summary performance information.
The Profile
class records how many times, and how long between Start and End, each named profile is called, outputting summary information about these executions when PrintResuls()
is called.
3.15.228.246