Measuring the Performance of your Code using a Timer

Hi everyone,
I had to fiddle with this recently to see which approach for doing squares was faster - Math.pow or a simple x*x. Hopefully the approach for using a timer to measure the time it takes to perform a computation proves helpful for you in other cases as well:


package 
{

	import flash.display.MovieClip;
	import flash.utils.getTimer;


	public class MainDocument extends MovieClip
	{
		public function MainDocument()
		{
			// constructor code


			var startingTime:Number = getTimer();

			for (var i:Number = 0; i < 10000; i++)
			{
				var randomA:Number = Math.random() * 1000;
				var randomB:Number = Math.random() * 1000;
				var randomC:Number = Math.random() * 1000;
				var randomD:Number = Math.random() * 1000;
				
				//
				// Toggle the commenting on the lines below to see which performs faster
				//
				var distance:Number = GetDistanceSquare(randomA,randomB,randomC,randomD);
				//var distance:Number = GetDistanceSquare(randomA,randomB,randomC,randomD);
			}
			
			var endingTime:Number = getTimer();
			
			trace("Starting time: " + startingTime + ", ending time: " + endingTime);
			trace(endingTime - startingTime);
		}

		private function GetDistancePow(xA:Number, yA:Number, xB:Number, yB:Number):Number
		{
			return Math.sqrt(Math.pow(xA - xB,2) + Math.pow(yA - yB,2));
		}

		private function GetDistanceSquare(xA:Number, yA:Number, xB:Number, yB:Number):Number
		{
			var xDiff:Number = xA - xB;
			var yDiff:Number = yA - yB;

			return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
		}
	}

}

Cheers,
Kirupa :write: