Stumbled upon this post as I’m in the process of optimizing my app. This is in response to “how to get the fps count”. While the ways outlined in this post are exactly the ways to do it, here’s an implementation of a graphical output to the screen of the fps count and memory usage:
PerformanceOutput = {};
PerformanceOutput.mt = {};
PerformanceOutput.mt.\_\_index = PerformanceOutput;
local prevTime = 0;
local maxSavedFps = 30;
local function createLayout(self)
local group = display.newGroup();
self.memory = display.newText("0/10",20,0, Helvetica, 15);
self.framerate = display.newText("0", 30, self.memory.height, "Helvetica", 20);
local background = display.newRect(-50,0, 175, 50);
self.memory:setTextColor(255,255,255);
self.framerate:setTextColor(255,255,255);
background:setFillColor(0,0,0);
group:insert(background);
group:insert(self.memory);
group:insert(self.framerate);
return group;
end
local function minElement(table)
local min = 10000;
for i = 1, #table do
if(table[i] \< min) then min = table[i]; end
end
return min;
end
local function getLabelUpdater(self)
local lastFps = {};
local lastFpsCounter = 1;
return function(event)
local curTime = system.getTimer();
local dt = curTime - prevTime;
prevTime = curTime;
local fps = math.floor(1000/dt);
lastFps[lastFpsCounter] = fps;
lastFpsCounter = lastFpsCounter + 1;
if(lastFpsCounter \> maxSavedFps) then lastFpsCounter = 1; end
local minLastFps = minElement(lastFps);
self.framerate.text = "FPS: "..fps.."(min: "..minLastFps..")";
self.memory.text = "Mem: "..(system.getInfo("textureMemoryUsed")/1000000).." mb";
end
end
local instance = nil;
-- Singleton
function PerformanceOutput.new()
if(instance ~= nil) then return instance; end
local self = {};
setmetatable(self, PerformanceOutput.mt);
self.group = createLayout(self);
Runtime:addEventListener("enterFrame", getLabelUpdater(self));
instance = self;
return self;
end
Usage (for example, in main.lua):
local performance = PerformanceOutput.new();
performance.group.x, performance.group.y = display.contentWidth/2, 0;
It outputs the current fps and the lowest fps among the last maxSavedFps (the variable defined at the top of the class) frames in brackets.
Edit : also, the way the code is written now, only a single instance of this class can be created without inducing bogus results (due to me using a local variable for things like the time of the previous frame, instead of a variable stored in the object). However, I doubt there’s really a use case in using two of these, so I don’t see a practical reason to change this
(I use this style with singletons a lot, because it kind of resembles private variables of a singleton class; table members are all public-like, so I avoid them where possible)
Another edit: changed it to be impossible to create 2 instances by using a local instance variable
[import]uid: 8145 topic_id: 2726 reply_id: 8586[/import]