I am trying to compare performance for 3d applications on mobile devices. I have a 3d solar system set up in webGL and im trying to record or at least display the FPS. So far this is what i Have:
in the body
<script language="javascript">
var x, message;
x = Time;
message = "fps is equal to ";
document.write (message); // prints the value of the message variable
document.write (x); //prints the value of x
</script>
and to get The Time Var in the draw function of canvas i have this
var Time = 0;
function drawScene() {
var startTime = new Date();
//draw scene here
var endTime = new Date();
Time = (endTime - startTime)
}
the output i get at the bottom of the canvas is "fps is equal to null"
any help would be great!
Since none of the other answers addressed the "in WebGL" part of the question, I'll add the following important details when measuring FPS in WebGL correctly.
For simplicity I used the console timer. I'm trying to make the point to always use WebGLRenderingContext.finish() to ensure the correct time is measured as all WebGL calls to the GPU are asynchronous!
I assume you are calling drawScene repeatedly but if you are setting
x
only once then it will not update every time drawScene is called. Also what you are storing inTime
is elapsed time and not frames per second.How about something like the below? The idea is to count the number of frames rendered and once one second has passed store that in the fps variable.
I created an object oriented version of Barış Uşaklı's answer. It also tracks the average fps over the last minute.
Usage:
global Variable:
Create the object somewhere when starting your program:
Call the update method in your draw() funktion & update the fps-displays:
Note: I only put the fps-display updates in the draw function for simplicity. With 60fps it gets set 60 times per second, even though once a second is enough.
FpsCounter Code:
OverrideBuffer Code:
Using a rotating array can do better. with dom element:
the following script do the trick:
Displaying FPSs is pretty simple and has really nothing to do with WebGL other than it's common to want to know. Here's a small FPS display
Use requestAnimationFrame for animation because that's what it's for. Browsers can sync to the screen refresh to give you buttery smooth animation. They can also stop processing if your page is not visible. setTimeout on the other hand is not designed for animation, will not be synchronised to the browser's page drawing.
You should probably not use
Date.now()
for computing FPS asDate.now()
only returns milliseconds. Also using(new Date()).getTime()
is especially bad since it's generating a newDate
object every frame.requestAnimationFrame
already gets passed the time in microseconds since the page loaded so just use that.It's also common to average the FPS across frames.