Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating FPS in Javascript less than 1 millisecond

Tags:

javascript

Is it possible to measure time gaps less than 1 milliseconds that is supported in all browsers i know of only one way which is in Chrome.

The chrome method : window.performance.now()

Currently i do FPS measurements in millisecond time spaces, but if less than 1ms passes i get infinity because the two numbers are rounded to nearest millisecond so they are the same value.

Does any one know a cross browser function calculate less than 1 millisecond time gaps in javascript?

like image 967
Sir Avatar asked Feb 21 '13 22:02

Sir


1 Answers

Here's how you get accurate measurements without an accurate timer, so long as what you're timing occurs often, which I'm hoping they do in your case.

Average/aggregate the imprecise measurements of the duration of your event. A snippet out of one of my projects:

        var start = Date.now();
        ... (stuff to be timed)
        var now = Date.now();

        if (DEBUG.enabled) {
            var profile_this_iter = now - start;
            profile += (profile_this_iter - profile) * 0.02;
        }

Each new value measures nudges your reading closer to it by a factor of 0.02. Obviously you'll want to tweak that a bit. This will allow you to read an average that hovers around 0.5ms if you read a duration of 1ms half the time and 0ms half the time (with a 1ms resolution timer).

This is obviously not a replacement for a proper higher resolution timer. But I use this simple algorithm to give my javascript projects a non-crappy FPS reading. You get a damping factor that you can tweak depending on if you want more accuracy or more immediate response to changes. Considering the simplicity of this one, you'd be hard pressed to find a more elegant algorithm to provide you a good representation without any improved input data. One of the ways to enhance it would be to adjust the approach factor (that 0.02 constant) based on the frequency of sampling itself (if that changes), this way a slower measured rate could be made to converge more quickly than with a fixed value.

like image 130
Steven Lu Avatar answered Oct 12 '22 12:10

Steven Lu