The example in this article describes how Android measures the number of frames per second (fps) by frames the Second. Share to everyone for your reference. Specifically as follows:
Mainthread.java:
Package Net.obviam.droidz;
Import Java.text.DecimalFormat;
Import Android.graphics.Canvas;
Import Android.util.Log;
Import Android.view.SurfaceHolder; /** * @author Impaler * * The Main thread which contains the game loop.
The thread must have access to * the surface view and holder to trigger events every game.
* * public class Mainthread extends Thread {private static final String TAG = MainThread.class.getSimpleName ();
Desired FPS private final static int max_fps = 50;
Maximum number of frames to be skipped private final static int max_frame_skips = 5;
The frame period private final static int frame_period = 1000/max_fps; Stuff for Stats * * Private decimalformat DF = new DecimalFormat ("0.##"); 2 DP//We ll be reading the stats every second private final static int stat_interval = 1000;
MS//The average is calculated by storing//the last n FPSS private final static int fps_history_nr = 10; Last time the status is stored PrivaTe long laststatusstore = 0;
The status Time counter private long Statusintervaltimer = 0l;
Number of frames skipped since the game started private long totalframesskipped = 0l;
Number of frames skipped in a store cycle (1 sec) Private long framesskippedperstatcycle = 0l;
Number of rendered frames in interval private int framecountperstatcycle = 0;
Private long totalframecount = 0l;
The last FPS values private double fpsstore[];
The number of times the stat has been read private long statscount = 0;
The average FPS since the game started private double averagefps = 0.0;
Surface holder that can access the physical Surface private Surfaceholder surfaceholder;
The actual view is handles inputs//and draws to the surface private maingamepanel gamepanel;
Flag to hold game state private Boolean running;
public void Setrunning (Boolean running) {this.running = running; Public Mainthread (Surfaceholder Surfaceholder, MaingamepanEl Gamepanel) {super ();
This.surfaceholder = Surfaceholder;
This.gamepanel = Gamepanel;
@Override public void Run () {Canvas Canvas;
LOG.D (TAG, "Starting game loop");
Initialise timing elements for stat gathering inittimingelements (); Long BeginTime; The time the cycle begun long Timediff; The time it is took for the cycle to execute int sleeptime; Ms to-sleep (<0 if we ' re behind) int framesskipped;
Number of frames being skipped sleeptime = 0;
while (running) {canvas = null; Try locking the canvas for exclusive pixel editing//In the surface try {canvas = This.surfaceHolder.lockCa
Nvas ();
Synchronized (surfaceholder) {begintime = System.currenttimemillis (); framesskipped = 0;
Resetting the frames skipped//update game State this.gamePanel.update ();
Render state to the "screen//Draws" canvas on the panel this.gamePanel.render (canvas); Calculate how LonG did the cycle take Timediff = System.currenttimemillis ()-begintime;
Calculate sleep Time Sleeptime = (int) (FRAME_PERIOD-TIMEDIFF); if (Sleeptime > 0) {//If Sleeptime > 0 we ' re OK try {//Send the thread to sleep for a short p
Eriod//Very useful for battery saving thread.sleep (sleeptime);
catch (Interruptedexception e) {}} while (Sleeptime < 0 && framesskipped < max_frame_skips) { We need to catch up this.gamePanel.update (); Update without rendering sleeptime + = Frame_period;
Add frame period to check if in next frame framesskipped++;
} if (framesskipped > 0) {log.d (TAG, "skipped:" + framesskipped);
}//For statistics framesskippedperstatcycle + = framesskipped;
Calling the routine to store the gathered statistics storestats (); finally {//In case of ' an exception the ' surface is ' not ' left IN//A inconsistent state if (canvas!= null) {surfaceholder.unlockcanvasandpost (canvas); }//End finally}/** * The statistics-it are called every cycle, it checks if time since last * store is Greater than the statistics gathering period (1 sec) and if so * it calculates "FPS for" last period and stores I T. * * * It tracks the number of frames per period. The number of frames since * the start of the period are summed up and the calculation takes part * only if the next P
Eriod and the frame count is reset to 0.
* * private void Storestats () {framecountperstatcycle++;
totalframecount++;
Check the actual time Statusintervaltimer + = (System.currenttimemillis ()-Statusintervaltimer); if (statusintervaltimer >= Laststatusstore + stat_interval) {//Calculate the actual frames status check pers
Val Double actualfps = (double) (Framecountperstatcycle/(stat_interval/1000)); Stores the latest FPS in theArray fpsstore[(int) Statscount% fps_history_nr] = Actualfps;
Increase the number of times statistics was calculated statscount++;
Double totalfps = 0.0;
Sum up the stored FPS values for (int i = 0; i < FPS_HISTORY_NR; i++) {totalfps = Fpsstore[i]; }//Obtain the average if (Statscount < FPS_HISTORY_NR) {//In case of the ' the ' of the ' the ' the ' triggers averagefps
= Totalfps/statscount;
else {averagefps = TOTALFPS/FPS_HISTORY_NR;
}//Saving the number of total frames skipped totalframesskipped + = framesskippedperstatcycle;
Resetting the counters after a status record (1 sec) framesskippedperstatcycle = 0;
Statusintervaltimer = 0;
framecountperstatcycle = 0;
Statusintervaltimer = System.currenttimemillis ();
Laststatusstore = Statusintervaltimer;
LOG.D (TAG, "Average FPS:" + Df.format (averagefps));
Gamepanel.setavgfps ("FPS:" + Df.format (averagefps));
}} private void Inittimingelements () { Initialise timing Elements Fpsstore = new DOUBLE[FPS_HISTORY_NR];
for (int i = 0; i < Fps_history_nr i++) {fpsstore[i] = 0.0;
LOG.D (TAG + ". Inittimingelements ()", "Timing elements for Stats initialised");
}
}
I hope this article will help you with your Java programming.