Friday, September 17, 2010

Javascript measurement tools

There are two important factor which has to be measured to identify the improvement in the code
  • Time taken to complete some operation
  • Memory usage of the application
Below is the example code for measuring the time.
<html>
    <head>
        <title>Time measurement tool</title>
        <script>
        function measureTimeElapsed()
        {
            var divlogoutput;
            var starttime;
            var endtime;
            var timeelapsed;
            starttime=(new Date()).getTime();
            for(var i=0;i<10000;i++)
            {
                var temp=parseInt("10");
            }
            endtime=(new Date()).getTime();
            timeelapsed=endtime-starttime;
            divlogoutput=document.getElementById("logoutput");
            //append the timeelapsed
            divlogoutput.innerHTML="<b>TimeElapsed:"+
                timeelapsed+"(milliseconds)</b><br/>";
        }
        </script>
    </head>
    <body onload="measureTimeElapsed()">
        <div id="logoutput">
        </div>
    </body>
</html>
Output:
Chrome 6.0:TimeElapsed:1(milliseconds)
Safari 3.2:TimeElapsed:10(milliseconds)
IE 7.0:TimeElapsed:27(milliseconds)
Mozilla Firefox:3.0.3:1(milliseconds)

Note: Profiling tools can be used for the measuring execution time and memory leak.

Note: If you are testing with Google Chrome or Mozilla Firefox then try console.time(name); and console.timeEnd(name);. Please refer Console API

No comments: