| versions | 0135+ |
|---|---|
| contributors | mflux |
| started on | 2009-09-25 17:39 |
Framerate is defined as “frames per second”. This is different from when you do frameRate(). The frameRate() function sets Processing to attempt drawing at that rate. This “hack” simply measures the actual frames per second being drawn by processing. You should know this if you play plenty of video games… fps is good!
In this example move your mouse left/right across the applet to spawn lines. These lines directly influence how fast the rendering happens. As rendering slows, your “fps” lowers.
Also notice how by default Processing is capped at 60fps.
/** fpscounter taken from http://processinghacks.com/hacks:fpscounter @author mflux */ // The framerate counter // To use this you must first do FPS.register(this) in your setup() static public class FPS { static private int frames = 0; static private long startTime = 0; static private int fps = 0; static private PApplet p; static FPS instance; public static void register(PApplet p){ instance = new FPS(); FPS.p = p; p.registerPost(instance); } public static void frame() { if (startTime==0) startTime = p.millis(); frames++; long t = p.millis() - startTime; if (t>1000) { fps = (int)(1000*frames/t); startTime += t; frames = 0; } } static public int frameRate(){ return fps; } public void post(){ FPS.frame(); } } // example code to use this with PFont font; void setup(){ size(400,400); FPS.register(this); font = createFont("Arial-Bold", 12); } void draw(){ background(255); // draw a bunch of lines to see how it holds up int numLines = mouseX * mouseX / 100; stroke(0,70); for(int i=0;i<numLines; i++){ float x1 = random(width); float y1 = random(height); float x2 = random(width); float y2 = random(height); line(x1,y1,x2,y2); } // draw the fps counter noStroke(); fill(0); textFont(font,12); text("frames per second: " + FPS.frameRate(), 6, 14); text("lines drawn: " + numLines, 6, 28); }
Notice how you never manually instantiate the class. This is a dirty way to do a “singleton”, meaning that only one instance should ever exist and need to exist for it to perform its job.
The actual framerate measuring happens on FPS.frame(). I've added a hook to automatically measure the fps at the end of draw() using Processing's built-in post(), however you can remove that and manually measure the framerate anywhere you please.
You'll also notice that the framerate actually updates once per second. This is to get an “average” of the framerate over a one second time period.