0

I've started using performance API in javascript to analyze the execution time of functions. The code is given below:

var iniT,finT;
iniT = performance.now();
functionCall();
finT = performance.now();
console.log(finT-iniT);

When I run this code multiple times, each time I get different outputs even though the code and the values involved are the same. Sometimes the difference is as much as +80%. (I am talking about milliseconds, but still...).

Sample o/p:

6.053819752878553
9.16106501362151
5.987994283801299

Is there anyway to make these outputs to have a lesser variance from each other? Not just asking about the code above, but are there any better alternative profiler? Is there anything I could do to the development environment (I am using the latest Chrome, not many extensions)?

(For instance, would iterating this in a loop and taking the average be better way to go?)

BlackPanther
  • 1,617
  • 1
  • 11
  • 18
  • 1
    Stop all background task on your computer, run the benchmarks while idle. Run them multiple times. Take the minimum (or median), not the average. – Bergi Jul 19 '16 at 11:19
  • 'Taking the median' is helpfull. Thanx. But did you mean to say 'stop all background tasks on browser'? or on the computer? – BlackPanther Jul 20 '16 at 09:46
  • OK. I tried running Windows in Safe Mode. Didn't cause much change. But, when I disabled the debugging add-on and all other otherwise inactive features, like PDF viewer, Flash player, etc.. it did bring about a considerable difference. – BlackPanther Jul 20 '16 at 10:09
  • Are there anymore suggestions? Is `performance` api the best I could use? If not, would you like to post these as an answer? – BlackPanther Jul 20 '16 at 10:11
  • Any more suggestions are just [basic benchmarking](http://stackoverflow.com/q/1003855/1048572) and [measuring solutions](http://stackoverflow.com/q/111368/1048572), about [choosing the right pattern](http://calendar.perfplanet.com/2010/bulletproof-javascript-benchmarks/) and [not writing microbenchmarks that get eaten by optimisers for breakfast](https://www.youtube.com/watch?v=65-RbBwZQdU). – Bergi Jul 20 '16 at 11:26

0 Answers0