2

I have a generative art app, and I'd like it to draw as many cycles as possible each frame without reducing the framerate. Is there a way to tell how much time is left until the screen updates/refreshes?

I figure if I can approximate how many milliseconds each cycle takes, then I can run cycles until the amount of time left is less than the average or the peak cycle time, then let the screen refresh, then run another set of cycles.

Mar
  • 7,765
  • 9
  • 48
  • 82
  • this may depend a lot also on the hardware you are running the app on. – Adrian Pirvulescu Feb 13 '12 at 17:33
  • I think if you output the FPS to the screen and use the Event.RENDER for updates you should be able to see if you are starting to hog the cpu, its trial and error, but will vary on different hardware. – Neil Feb 13 '12 at 17:46

2 Answers2

4

If you want your app to run at N frames per second, then you can draw in a loop for 1/N seconds*, where N is typically the stage framerate (which you can get and set):

import flash.utils.getTimer;
import flash.events.Event;

private var _time_per_frame:uint;

... Somewhere in your main constructor:

stage.frameRate = 30;
_time_per_frame = 1000 / stage.frameRate;
addEventListener(Event.ENTER_FRAME, handle_enter_frame);

...

private function handle_enter_frame(e:Event):void
{
  var t0:uint = getTimer();

  while (getTimer()-t0 < _time_per_frame) {
    // ... draw some stuff
  }
}
  • Note that this is somewhat of a simplification, and may cause a slower resultant framerate than specified by stage.frameRate, because Flash needs some time to perform the rendering in between frames. But if you're blitting (drawing to a Bitmap on screen) as opposed to drawing in vector or adding Shapes to the screen, then I think the above should actually be pretty accurate.

If the code results in slower-than-desired framerates, you could try something as simple as only taking half the allotted time for a frame, leaving the other half for Flash to render:

_time_per_frame = 500 / stage.frameRate;

There are also FPS monitors around that you could use to monitor your framerate while drawing. Google as3 framerate monitor.

Jeff Ward
  • 16,563
  • 6
  • 48
  • 57
  • Worked the principle behind this into my code, and it works great! Basic idea: get the time at the start of a frame, and do your loop until the time is 1 frame's-worth of time later, then draw. – Mar Mar 22 '12 at 22:07
0

Put this code to main object and check - it will trace time between each frame start .

addEventListener(Event.ENTER_FRAME , oef);
var step:Number = 0;
var last:Number = Date.getTime();
function oef(e:Event):void{
    var time:Number = Date.getTime();
    step = time - last;
    last = time;

    trace(step);
}
turbosqel
  • 1,542
  • 11
  • 20