JavaScript Profiling
var Timer = {
_data: {},
start: function(key) {
Timer._data[key] = new Date();
},
stop: function(key) {
var time = Timer._data[key];
if (time) {
Timer._data[key] = new Date() - time;
}
},
getTime: function(key) {
return Timer._data[key];
}
};
Timer.start('createElement');
for (i = 0; i < count; i++) {
element = document.createElement('div');
}
Timer.stop('createElement');
alert('created ' + count + ' in ' + Timer.getTime('createElement');
YUI Profiler
Firebug
Internet Explorer Developer Tools
Safari Web Inspector
Chrome Developer Tools
Page Speed
Fiddler
Yslow
dynaTrace Ajax Edition
/**
* Figure out how long it takes for a method to execute.
*
* @param {func} method to test
* @param {int} iterations number of executions.
* @param {Array} args to pass in.
* @param {T} context the context to call the method in.
* @return {int} the time it took, in milliseconds to execute.
*/
var bench = function (method, iterations, args, context) {
var time = 0;
var timer = function(action) {
var d = +(new Date);
if (time < 1 ||action === 'start') {
time = d;
return 0;
} else if (action ==='stop') {
var t = d - time;
time = 0;
return t;
} else {
return d -time;
}
};
var result = [];
var i = 0;
timer('start');
while (i < iterations) {
result.push(method.apply(context, args));
i++;
}
var execTime =timer('stop');
if ( typeof console ==="object") {
console.log("Meanexecution time was: ", execTime / iterations);
console.log("Sumexecution time was: ", execTime);
console.log("Resultof the method call was:", result[0]);
}
return execTime;
};
Readingout the end time in browser speed tests
源文档 <http://www.quirksmode.org/blog/archives/2009/08/when_to_read_ou.html>
function testIt() {
var startTime = new Date().getTime();
// actual DOM functionality to be tested goes here
var endTime = new Date().getTime();
var result = (endTime-startTime)/1000;
// print result
}
So what really happens here is the following:
1.Get start time
2.Perform DOM manipulation in browser memory
3.Get end time and calculate result
4.The function ends, and only now does the browser start to apply the results of the DOM manipulation to the actual DOM.
function testIt() {
var startTime = new Date().getTime();
// actual DOM functionality to be tested goes here
setTimeout(function () {
var endTime = new Date().getTime();
var result = (endTime-startTime)/1000;
// print result
},10)
}
What happens now is the following:
1.Get start time
2.Perform DOM manipulation in browser memory
3.Define a function to get end time and calculate result and set a timeout
4.The function ends, and only now does the browser start to apply the results of the DOM manipulation to the actual DOM.
5.Once the DOM manipulation is finished, the browser is freed up to treat the timeout we set, and now the function that gets the end time and shows the result is executed.