Home Tutorials Forums Articles Blogs Movies Library Employment Press

 ActionScript.org Forums Math.sin is really fast
 User Name Remember Me? Password
 Register FAQ Members List Social Groups Calendar Search Today's Posts Mark Forums Read

 11-15-2008, 10:16 PM #1 pj-co Site Contributor     Join Date: Jun 2008 Location: Brooklyn Posts: 360 Math.sin is really fast So I though I was being all fancy by pre-calculating out some values for Math.sin in a project I was working on a few weeks ago. But I just ran some speed tests and found out some interesting things. First here's my LookupTable class: For now, ignore the granularity option as we'll work with just ints. Also, it's important not to perform int->Number or Number->int conversion ActionScript Code: ```package com.pj_co.math {     /**      * Generates a sine or cosine curve based on max and min values.  These values are inteperated      * as 0 and 90 degrees on a graph respectively. This allows for retuning a single curve.      * The equations used are:  Math.sin ( i / maxVal  * PI )  and  Math.cos ( i / maxVal  * PI )      *      * @author Patrick Cousins      */     public class LookupTable     {               public static const SINE     : String = "sine";         public static const COSINE   : String = "cosine";         public static const BOTH     : String = "both";                 private var sinTable         : Array;         private var cosTable         : Array;         private var maxVal           : Number;                 public function LookupTable (   type         : String,                                         minVal       : Number,                                         maxVal       : Number,                                         granularity  : Number    = 1     )         {                         this.minVal = minVal;             this.maxVal = maxVal;                                     switch ( type )             {                                 case SINE :                     generateSineTable ( minVal, maxVal, granularity);                                break;                                 case COSINE :                     generateCoSineTable ( minVal, maxVal, granularity);                      break;                                 case BOTH :                     generateCoSineTable ( minVal, maxVal, granularity);                     generateSineTable ( minVal, maxVal, granularity);                 break;             }         }                 //-------------------------------------------------------         // Public API         //-------------------------------------------------------                         public function getCosine( val : Number ) : Number         {                               return cosTable[val];         }                 public function getSine( val : int ) : Number         {                      return sinTable[val];         }                 public function getSineArray(  ) : Array         {                      return sinTable;         }                 //-------------------------------------------------------         // Private methods         //-------------------------------------------------------                                 private function generateCoSineTable (  minVal     : Number,                                                 maxVal   : Number,                                                 granularity : Number        ) : void         {                         cosTable = new Array();                         var PI :Number = 3.1415927;                         for (var i : Number = minVal; i <= maxVal; i += granularity)             {                             cosTable [i] = ( Math.cos( i / maxVal  * PI ) );                            }         }                         private function generateSineTable (    minVal       : Number,                                                 maxVal   : Number,                                                 granularity : Number        ) : void         {                         sinTable = new Array();                         var PI :Number = 3.1415927;                         for (var i : Number = minVal; i <= maxVal; i ++ )             {                             sinTable.push ( Math.sin( i / maxVal  * PI ));                    }         }             } }``` Ok now for some test code: ActionScript Code: ```import com.pj_co.math.LookupTable; var lookupTable : LookupTable = new LookupTable ( LookupTable.SINE, 0, 500, 1 ); var sineTable:Array = lookupTable .getSineArray(); //set a time point var now : Date = new Date(); for (var i : Number = 0 ; i < 999999 ; i++ ) {     var realSine : Number = Math.sin ( i / 500  * Math.PI );    } //set a second time point var after : Date = new Date(); for (var j : int = 0 ; j < 999999 ; j++ ) {     var localArraySine : Number = sineTable[j]; } //set a third time point var after2 : Date = new Date(); for (var k : int = 0 ; k < 999999 ; k++ ) {     var computedSine : Number = lookupTable.getSine(k);     } //set a fourth time point var after3 : Date = new Date(); //calculate the time differences var diffSeconds1 = after.getSeconds() - now.getSeconds(); var diffMiliseconds1 = after.getMilliseconds() - now.getMilliseconds(); if ( diffMiliseconds1 < 0 ) {     diffSeconds1 --;     diffMiliseconds1 += 1000; }     var diffSeconds2 = after2.getSeconds() - after.getSeconds(); var diffMiliseconds2 = after2.getMilliseconds() - after.getMilliseconds(); if ( diffMiliseconds2 < 0 ) {     diffSeconds2 --;     diffMiliseconds2 += 1000; }     var diffSeconds3 = after3.getSeconds() - after2.getSeconds(); var diffMiliseconds3 = after3.getMilliseconds() - after2.getMilliseconds(); if ( diffMiliseconds3 < 0 ) {     diffSeconds3 --;     diffMiliseconds3 += 1000; } trace("1st for loop (Math.Sin) :",        diffSeconds1,        "seconds ",        diffMiliseconds1,        "milliseconds" ); trace("2nd for loop (local pre-computed array) :",        diffSeconds2,        "seconds ",        diffMiliseconds2,        "milliseconds" ); trace("3rd for loop (precomputed from lookuptable getter method ) :",         diffSeconds3,        "seconds ",        diffMiliseconds3,        "milliseconds" );``` So after nearly a million iterations in each for loop, the results were : 1st for loop (Math.Sin) : 0 seconds 281 milliseconds 2nd for loop (local, pre-computed array) : 0 seconds 141 milliseconds 3rd for loop (precomputed sine retrieved from lookuptable getter method ) : 0 seconds 281 milliseconds Last edited by pj-co; 11-15-2008 at 10:38 PM.
11-15-2008, 10:34 PM   #2
lordofduct
Senior Member

Join Date: Feb 2008
Location: West Palm Beach, FL
Posts: 3,872

You should always keep this comment on the livedocs for the Math class in mind when considering the speed of trig functions:

Quote:
 Note: The Math functions acos, asin, atan, atan2, cos, exp, log, pow, sin, and sqrt may result in slightly different values depending on the algorithms used by the CPU or operating system. Flash Player calls on the CPU (or operating system if the CPU doesn't support floating point calculations) when performing the calculations for the listed functions, and results have shown slight variations depending upon the CPU or operating system in use.
Different processors solve trig functions differently.

I've always wondered what methods are used by the FPU to solve it... in the cases of processors with some floating point engine (which most modern processors do have). Of all the methods I know of to do it on paper, they all are very time consuming.
__________________
www.lordofduct.com - come read my blog!

If you want to know how to program, take a math class, take a lot of math classes!

 11-15-2008, 10:36 PM #3 pj-co Site Contributor     Join Date: Jun 2008 Location: Brooklyn Posts: 360 Good point lord. The above is tested on a PC (win XP) and i'll give it a go at work on my mac. Could you test it on your linux box though? Would love to see how it did there.
11-15-2008, 10:43 PM   #4
lordofduct
Senior Member

Join Date: Feb 2008
Location: West Palm Beach, FL
Posts: 3,872

Quote:
 Originally Posted by pj-co Good point lord. The above is tested on a PC (win XP) and i'll give it a go at work on my mac. Could you test it on your linux box though? Would love to see how it did there.
sure:

Quote:
 1st for loop (Math.Sin) : 0 seconds 268 milliseconds 2nd for loop (local pre-computed array) : 0 seconds 166 milliseconds 3rd for loop (precomputed from lookuptable getter method ) : 0 seconds 448 milliseconds
compiled in Eclipse with FlexBuilder 3 plug-in.

Computer specs:
Intel Core2Duo E6700 2x2.67Ghz
2GB DDR2 800mhz
Asus board with nForce4 chipset
OS: Ubuntu 8.10 -intrepid w/ gnome

Ran using FlashPlayer10.so debug version.

Keep in mind the FlashPlayer written for Linux runs much slower then the Mac and Windows versions. And I've noticed a lot of things that don't work in it...
__________________
www.lordofduct.com - come read my blog!

If you want to know how to program, take a math class, take a lot of math classes!

Last edited by lordofduct; 11-15-2008 at 10:45 PM.

 11-15-2008, 11:08 PM #5 pj-co Site Contributor     Join Date: Jun 2008 Location: Brooklyn Posts: 360 Cool thanks. Seems object access is really what slows it down in both cases.
 11-16-2008, 04:54 PM #6 pj-co Site Contributor     Join Date: Jun 2008 Location: Brooklyn Posts: 360 By the way if anyone has a Mac and is bored I won't stop you guys from testing __________________ http://pajamacode.pj-co.com/

 Thread Tools Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is Off Forum Rules
 Forum Jump User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home ActionScript Forums Group     ActionScript 3.0     ActionScript 2.0     ActionScript 1.0 (and below)     Simple Stuff (Newbies) Flash General Questions     Flash 10 General Questions     Flash 9 General Questions     Flash 8 General Questions     Other Flash General Questions Flex     Flex 2, 3 & 4     Flex 1 Extensions and Plugins     Components     JSFL - Extending Flash Desktop, Mobile and non-browser Environments     AIR (Apollo)     FlashLite / Portable Devices Development     Projectors and CDs Supporting Technologies     HTML and JavaScript     haXe     Server-Side Scripting     Flash Remoting     Flash Media Server General     Best Practices     Gaming and Game Development     Animation and Effects     Flashants Support Forum Community Boards     General Chat     Just for Kicks Challenges     Detention Flash In Action     Site Check     Cool Sites     Widgets Decommissioned     Projects and Positions CMS Forums     Announcements Board     Content Postings / Updates     Product Review Requests     CMS Technical Questions     Process Questions     Collaboration & Suggested Articles

 Similar Threads Thread Thread Starter Forum Replies Last Post wonko ActionScript 2.0 2 10-26-2006 11:03 AM kreven ActionScript 2.0 0 06-16-2006 05:37 AM dreamline ActionScript 2.0 4 08-01-2005 02:59 AM buzzby ActionScript 1.0 (and below) 1 10-29-2004 12:43 PM infiniti Animation and Effects 6 08-19-2004 08:40 PM

All times are GMT. The time now is 09:27 PM.

///