开发者

How to measure how long the function works

开发者 https://www.devze.com 2023-04-09 16:16 出处:网络
I am trying to compare the performance of several different algorithms. So created several functions each of them implementing different approach of solving the same task.

I am trying to compare the performance of several different algorithms. So created several functions each of them implementing different approach of solving the same task.

What was thinking to do is to create 2开发者_StackOverflow中文版 Date objects before and after the function runs, and to compare them afterwords...

The issue here is that I need to modify the code for it, so maybe there another approach? Who can suggest?


Easy way: Use getTimer() when you start and then check and compare when the function is done.

Example: http://wonderfl.net/c/d5WS

package
{
    import flash.display.Sprite;
    import flash.utils.getTimer;
    import flash.text.TextField;

    public class FlashTest extends Sprite
    {

        private var _debugText : TextField;

        public function FlashTest()
        {
            var timeStarted : int = getTimer();
            var timeCompleted : int;

            runReallyWackyFunction();

            timeCompleted = getTimer();

            setupDebugText("total time: " + (timeCompleted - timeStarted) + "ms");
        }

        private function setupDebugText(message : String) : void
        {
            _debugText = new TextField();
            _debugText.x = 20;
            _debugText.y = 20;
            _debugText.textColor = 0xFFCC00;
            _debugText.backgroundColor = 0x000000;
            _debugText.background = true;
            _debugText.autoSize = "left";
            _debugText.text = message;
            addChild(_debugText);
        }

        private function runReallyWackyFunction() : void
        {
            // put wacky stuff here
            var testUpdates : int = 300000;

            while(testUpdates--)
            {
                with(graphics)
                {
                    beginFill(Math.random()*0x000000, 0.25);
                    drawCircle(Math.random() * stage.width, Math.random() * stage.height, 10);
                    endFill();
                }

            }

        }
    }

}


There are several ways to do this from scratch, but I would suggest trying Grant Skinner's Performance Test.

In addition to being able to test individual methods, it will allow you to set up a "Test Suite" which allows you to run tests on multiple methods multiple times, and average the results to find optimal performance.

Above, I've linked to the article explaining the newest version (2.0) instead of the download, hopefully you find this helpful. Also, he has several other entries about optimization, which are a fascinating read at worst, and invaluably helpful more often.

My favorite is his talk: Quick as a Flash

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号