Code: An FPS Counter

I was looking around for a simple way to compare FPS when I made changes - didn’t seem to be one readily available. I’ve grabbed the one out of the Island Demo and converted it to C# for anyone interested. Just drag it onto a GUIText.
thx to UT for the original JS version.

// Attach this to a GUIText to make a frames/second indicator.
//
// It calculates frames/second over each updateInterval,
// so the display does not keep changing wildly.
//
// It is also fairly accurate at very low FPS counts (<10).
// We do this not by simply counting frames per interval, but
// by accumulating FPS for each frame. This way we end up with
// correct overall FPS even if the interval renders something like
// 5.5 frames.

using UnityEngine;
using System.Collections;

public class fpsCounter : MonoBehaviour
{

    public float updateInterval = 1.0f;
    private float accum = 0.0f; // FPS accumulated over the interval
    private int frames = 0; // Frames drawn over the interval
    private float timeleft; // Left time for current interval
    private float fps = 15.0f; // Current FPS
    private float lastSample;
    private int gotIntervals = 0;

    void Start()
    {
        timeleft = updateInterval;
        lastSample = Time.realtimeSinceStartup;
    }

    float GetFPS() { return fps; }
    bool HasFPS() { return gotIntervals > 2; }

    void Update()
    {
        ++frames;
        float newSample = Time.realtimeSinceStartup;
        float deltaTime = newSample - lastSample;
        lastSample = newSample;

        timeleft -= deltaTime;
        accum += 1.0f / deltaTime;

        // Interval ended - update GUI text and start new interval
        if (timeleft <= 0.0f)
        {
            // display two fractional digits (f2 format)
            fps = accum / frames;
            guiText.text = "FPS: " + fps.ToString("f2");
            timeleft = updateInterval;
            accum = 0.0f;
            frames = 0;
            ++gotIntervals;
        }
    }
}

Actually, the one you converted comes from Time.realtimeSinceStartup docs (which in turn is an improved version of FramesPerSecond script on the wiki)…

…so there are FPS counters available :slight_smile:

oh well - at least there’s a c# version now :wink:

wish there was a google-like global search that crawled the docs and forum at once

Hush you, enough with your forum complaints! :stuck_out_tongue:

I’m kidding y’all, Shaun has offered me some well thought out ideas about forum improvements off-line, including some search updates. So I’m just having fun with him…

damn! got caught…

I’ve got new info on cross forum/doco search - have emailed :wink:

FWIW, the given code sample from the realtimeSinceStartup docs doesn’t work on Windows; it always displays “Infinity” rather than the actual fps count.

Sent as bug #15603

Right - I’ve just found that problem too… it appears to be cause by the number of digits after the point - as the framerate seems to not impact it.

Thanks guys, we’ll get on that and see about updating that code sample to work properly.

Ok, what happens is: depending on the CPU and the motherboard, you can get the system timer reporting exactly the same time for several consecutive frames (if frames are short). In Time.deltaTime we make sure that delta time is never zero (instead a very small number), but we don’t do this for Time.realtimeSinceStartup (because, well, it’s the “real time”). This causes divisions by zero in the FPS script.

I’m updating the example code to this instead, which is simpler to understand as well:

// A FPS counter.
// It calculates frames/second over each updateInterval,
// so the display does not keep changing wildly.
 
var updateInterval = 0.5;
private var lastInterval : double; // Last interval end time
private var frames = 0; // Frames over current interval
private var fps : float; // Current FPS

function Start()
{
    lastInterval = Time.realtimeSinceStartup;
    frames = 0;
}

function OnGUI ()
{
    // Display label with two fractional digits
    GUILayout.Label("" + fps.ToString("f2"));
} 

function Update()
{
    ++frames;
    var timeNow = Time.realtimeSinceStartup;
    if( timeNow > lastInterval + updateInterval )
    {
        fps = frames / (timeNow - lastInterval);
        frames = 0;
        lastInterval = timeNow;
    }
}

Yeah this feels like the old code… to which the problem under windows is that it shows crazy huge numbers.

Even when using: fps.ToString("f2", System.Globalization.CultureInfo.InvariantCulture.NumberFormat);

If it’s not one thing, it’s another! :stuck_out_tongue:

I’m not sure I understand the problem now… can you restate it so my limited language parser can grok it? :roll:

It blow up, no work good. :wink:

On his windows builds, and I think windows webplayers too, the FPS counter shows huge numbers (like 20k), while on Mac the FPS works properly and shows ~80 fps.

I pointed Casemon to the .NET Globalization for number format thread that Mat started, but it doesn’t seem to help at all.

Any ideas? (and Casemon can correct the numbers I said) :wink:
-Jeremy

Is no good. Problem must be! :slight_smile:

Seriously though, I don’t know. This fixed FPS script does work correctly on 2 PCs I tried…

  • Does Joe have any timing problems in the game, or it’s only the FPS script that is broken?
  • What if he tries utility like Fraps to display the FPS?
  • Can he send the game build and his machine specs in a bug report?

I can answer part of it, until Joe gets released from the treatment center.

  • Does Joe have any timing problems in the game, or it’s only the FPS script that is broken?
    IIRC he said the mouse input was also screwed up, but both problems are only on PC builds. Mac builds of the exact same setup have no problems at all.

Now I am done talking for Joe, feels like the exorcist movie :wink:

(Joe; no ventriloquist dummy jokes, or I am sending you back to the pound)

-Jeremy

Well it looks like all is well… I rebuilt the webplayer one last time and am getting reliable results in standalone and webplayer.

That 40fps limit on webplayer is really surprising… thinking there should be something in the docs about that (didn’t see any on first glance).

I’m sorry for wasting time on that last bit. Glad the new FPS script is working now… Thanks for jumping on this Aras.

joe
…who can now move on to bugging the fact that full screen effects (like fade) show a little of the background in the upper left and top edges on windows webplayer… :stuck_out_tongue: