As the framerate changes too quick when I just display 1.0 / DeltaTime each frame, I wanted to show an average frame rate over a number of frames to stabilize it more. Here you find the source code to this small class including a draw function.
Simplest usage is to initialize the class as framerate=FrameRateC(25, 100). Then call framerate:calc() and framerate:draw(1, 255) in your draw code, that shows the FPS as average over 25 frames and a history of 100 FPS. Initialize as FrameRateC(25, 0) to only show the number.
You can also retrieve the current average and frame number with getAverageFrameRate() and getCurrentFrameNr(). The average is calculated over 20 frames in this sample which I found good for my use cases.
The algorithm used is called Simple Moving Average. It avoids calculating the median over the whole table each frame, so the runtime is the same independent of the number of frames you average. But showing a large history will take time.
Have fun,
Kilam Malik
Source of Main function to test it:
-- Main.lua
frameRate = nil
frameNr = 1
frameAvg = 0
--displayMode(FULLSCREEN)
-- Use this function to perform your initial setup
function setup()
frameRate = FrameRateC(20, 100)
watch("frameNr")
watch("frameAvg")
iparameter("nrObjects", 1, 500, 50)
iparameter("position", 1, 4, 2)
iparameter("alpha", 50, 255, 127)
iparameter("bgcol", 0, 255, 255)
end
-- This function gets called once every frame
function draw()
frameNr = frameRate:getCurrentFrameNr()
frameAvg = frameRate:getAverageFrameRate()
-- This sets a dark background color
background(bgcol, bgcol, bgcol, 255)
-- This sets the line thickness
strokeWidth(5)
-- Do your drawing here
stroke(0, 0, 0, 127)
strokeWidth(1)
for i = 1, nrObjects do
local r = 200 + 100*math.sin(i*0.180)
local inner = (ElapsedTime*20+i)/20
local cs = math.sin(inner) + 1
local cc = math.cos(inner*0.3429495) + 1
fill(127*cs, 127*cc, 127*cs*cc, 50)
ellipse(WIDTH/2 + r*math.sin(inner),HEIGHT/2 + r*math.cos(inner),30)
end
-- Calc and draw the frame rate:
frameRate:calc()
frameRate:draw(position, alpha)
end