Giulio Muscarello
Giulio Muscarello

Reputation: 1341

Measuring JavaScript performance

I have a JavaScript file that takes an input, does some calculations with it, and returns a result. Now, I'd like to measure its performance, checking for example how much does it take to run 1.000 inputs. The problem is that I have nearly no knowledge of Javascript (the code isn't mine, neither), so I don't have any idea of how to do this. StackOverflowing I found some similar questions, but it's about "how much does it take for the script to run once" rather than "how much does it take for the script to elaborate 1.000 inputs".

If it can help, this is the script.

Upvotes: 1

Views: 1238

Answers (2)

hereandnow78
hereandnow78

Reputation: 14434

if you want to measure and analyze this script, you just need to grow your javascript knowledge (at least a little bit).

then you could use a benchmarking tool like benchmark.js. you can use it in your browser or within node.js.

jsperf.com uses benchmark.js. you could set up a testcase there which should be done within minutes. it is usually designed to compare 2 scripts, but you could just put your script into both tests and you have a first indication

Upvotes: 0

Johan
Johan

Reputation: 35213

I would do something like this (depending on if the window console exists and has the time property):

if('console' in window && 'time' in window.console){

    console.time('time');
    for (var k=0;k<1000;k++) {
        derp(input);
    }
    console.timeEnd('time');

} else {

    var d = new Date();
    for (var k=0;k<1000;k++) {
        derp(input);
    }
    console.log('result: ' + new Date().getTime() - d.getTime() + 'ms');

}

Upvotes: 2

Related Questions