How can I calculate how much time a function takes in jQuery?
I have jQuery functions; e.g A(), B() and C() Each function makes some Ajax calls to different sites.
I want to calculate how much time it takes to run each function (I guess in milliseconds) I just want to test my code in long loops and in different modern browsers (Safari/Chrome/IE10/Mozilla). More specifically, I want to calculate how much time it takes to take a callback from each Ajax request (this is also the time that the fun开发者_高级运维ction ends right?) How might I achieve this?
You could get the time in milliseconds from the date object.
var start = new Date().getTime();
A();
function AJAXSuccessFunction() {
console.log(new Date().getTime() - start);
}
//set start point anywhere you want
var start = new Date();
//when done,
var end = new Date();
//to profile milliseconds, just do
var duration = end - start;
Nowadays, you can use perfomance.now()
. This function uses the navigationStart
attribute as a start time;
This attribute must return the time immediately after the user agent finishes prompting to unload the previous document. If there is no previous document, this attribute must return the same value as fetchStart.
As for a real life code example:
// Store the start
var start = performance.now();
// Do some operation
for(var i=0; i < 1000; i++) {
var j = i*i;
}
// Profile the milliseconds it took to do the job
var duration = (performance.now() - start);
You can now use , console.time('fn1') and console.timeEnd('fn1')
So if you are calling a function like doAwesomeStuff() and want to see how much time it takes to execute it just do,
console.time('fn1')
doAwesomeStuff()
console.timeEnd('fn1')
fn1 - can be anything.
I don't know if this is what you're looking for but if you want to know how much time was spent processing a function, you can use Chrome's DevTools (or similar tools in other browsers) to check that.
Go to the page you want to examine, open DevTools, go to Profiles
tab and select 'Collect Javascript CPU profile' and hit Start
to start recording.
Refresh your page and when it has completed loading, Stop
the recording. You'll get a list of functions executed and time that was spent processing it.
Hope that helps.
You can use more precisely performance.now()
// Take a timestamp at the beginning.
var start = performance.now();
// Execute the code being timed.
console.log("your function is here")
// Take a final timestamp.
var end = performance.now();
// Calculate the time taken and output the result in the console
console.log('doTasks took ' + (end - start) + ' milliseconds to execute.');
精彩评论