Search This Blog

Thursday, May 2, 2013

ActionScript 3.0 - Natural vs. Event-based Delays

As the title of this blog hints there are going to be quite a few technical posts here. So here's the first one : It's about something I came across recently in Flash ActionScript 3.0.

The problem I faced was that I had to accurately measure time intervals in my SWF. As this was related to network diagnosis, small inaccuracies in the measurement would result in very large differences in the final result.

I wanted to see if the accuracy of measurement in Flash was comparable to the one in Java where we take the difference between the returned values of the System.currentTimeMillis() function at two different times. To do this I set up a Timer with a delay of 500ms that would run 10 times, calling a function on the completion of each run. This function would calculate the difference of the current getTimer() value and the one stored in startt (below).The results are added to a TextField "recordTimer" on the screen. This was the code for the above :

var records:Vector.<String> = new Vector.<String>();
var count:uint = 0;
var startt:Number = getTimer();
var q:Timer = new Timer(500, 10);


q.addEventListener(TimerEvent.TIMER, updq);
q.addEventListener(TimerEvent.TIMER_COMPLETE, compq);

q.start();

function updq(e:TimerEvent):void {
 temp = getTimer();
records[count] = String(temp - startt);
count++;
}


function compq(e:TimerEvent):void {
for(var j:uint = 0; j < 10; j++)
recordTimer.appendText(records[j] + "\n");

}  


However there was a problem with this code. Since events are related to the frame rate, there was a granularity of ~33ms in my result (I was running my SWF at 30fps) : 



So I decided to produce a natural delay instead and ran an empty for-loop 30 million times instead of using a Timer. This was the code I wrote :

var starttime:uint = getTimer();
var endtime:uint;
var j:uint = 0;
var i:uint = 0;

begin();

function begin():void {
    for(i = 0; i < 10; i++) {
    starttime = getTimer();
    for(j = 0; j < 30000000; j++);
    endtime = getTimer();
    results1.appendText(String(endtime - starttime) + "\n");
    }
}

This time the result was more to my liking :





As there were no events involved, there was no granularity in the results. Also, the values seemed to be accurate within ~1ms, which I think should be good enough for my cause !

I end this post with two key points :
1. Measuring time intervals in ActionScript 3.0 seems to be quite accurate
2. When using events, always keep the framerate you are using in mind

No comments:

Post a Comment