views:

86

answers:

2

I have some function I want to time, but I have no idea how to do it. In javascript I can just get the current time in milliseconds, run the rest of my function, get the current time in milliseconds again and alert the difference. Viola, I know how long the function ran.

In ActionScript, it runs everything at once, so my start and end times are the same. How can I measure the span of time a function is taking to process?

Thanks,

+5  A: 

Quick way below. It's better to do a statistical test, eg. run the toMeasure a 100 times between setting time1 and time2 and dividing the result by 100. It might give you a more realistic estimate. Remember that modern computers can do a bit of calculations in under a millisecond.

            private var time1:Number;
            private var time2:Number;

            private function toMeasure():void
            {
                for (var i:int = 0;i<30000;i++)
                {
                    trace (i);
                }
            }

            protected function main():void
            {
                time1= new Date().time;
                toMeasure();
                time2= new Date().time;
                trace ("ms:"+(time2-time1));
            }
Robert Bak
Yup, that should do it. As an extra, you can check out Grant Skiner's test utilities: http://www.gskinner.com/blog/archives/2009/04/as3_performance.html
George Profenza
you also could use flash.utils getTimer() to get a suitable timestamp for comparing times.
Hippo
A: 

To test the our functions in this thread: SO Thread

I did this

trace(timeTest(removeElements, [new XML(myXML.toString()), "hidden", "false"], 50));
trace(timeTest(remove, [new XML(myXML.toString())], 50));


public function timeTest(f:Function, args:Array, n:Number):Number {
    var t1:Number = new Date().getTime();

    for (var i:Number = 0; i < n; i++) {
        args[0] = new XML(args[0].toXMLString());
        f.apply(this, args);
    }

    var t2:Number = new Date().getTime();
    return (t2 - t1) / n;
}

The only "weird" thing here is the args[0] = new XML(args[0].toXMLString()); This was added because my method edited the XML in place, so after a single call the XML was already in the correct form and the method completed in a much shorter time. The extra overhead for creating new XML is the same for both methods so it is negligible.

sberry2A
awesome catch on linking the threads :)
invertedSpear