Optimization principal 4: Use performance data to drive design and coding decisions.
A useful raw measurement of game performance is the maximum and minimum frame rate for a section of a game. In this recipe, we make use of a Creative Commons Frames Per Second (FPS) calculation script to record the maximum and minimum frame rates for a game performing mathematics calculations for each frame.
For this recipe, we have provided C# script FPSCounter.cs
in the 1362_11_12
folder. This file is the one we have modified to include the maximum and minimum values based on the Do-It-Yourself (DIY) frame rate calculation script from Annop "Nargus" Prapasapong, kindly published under Creative Commons on the Unify wiki at http://wiki.unity3d.com/index.php?title=FramesPerSecond.
To calculate and record the maximum and minimum FPS, follow these steps:
FPSCounter.cs
script.FPSCounter
script class to the Main Camera.SomeCalculations
to the Main Camera:using UnityEngine; using System.Collections; public class SomeCalculations : MonoBehaviour { public int outerLoopIterations = 20; public int innerLoopMaxIterations = 100; void Update(){ 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); } } } }
The SomeCalculations
script ensures that we make Unity do something for each frame, in that it performs lots of calculations when the Update()
method is called for each frame. There is an outer loop (loop counter i
) of public variable outerLoopIterations
iterations (which we set to 20
), and an inner loop (loop counter j
), which is a random number of iterations between 2, and the value of public variable innerLoopMaxIterations
(which we set to 100
).
The work for the calculations of average Frames Per Second (FPS) is performed by the FPSCounter
script, which runs coroutine method FPS()
at the chosen frequency (which we can change in the Inspector). Each time the FPS()
method executes, it recalculates the average frames per second, updates the max and minimum values if appropriate, and, if the Display While Running checkbox was ticked, then a GUIText object on screen is updated with a message of the average, max, and min FPS.
Finally, the OnApplicationQuit()
method in script class FPSCounter
is executed when the game is terminated and prints to the console the summary max/min FPS message.
Some details you don't want to miss:
18.119.138.202