问题
I need to compare the computation speed of some code, but I'm not sure what the best way to do that is. Is there some kind of built-in timer to do this? And is it possible to get the computation speed in nanoseconds, or do I need to deal with the milliseconds JavaScript usually works with?
回答1:
I came across the performance API. What you're looking for is probably Performance.now()
, which will give you microsecond percision.
The
Performance.now()
method returns a DOMHighResTimeStamp, measured in milliseconds, accurate to one thousandth of a millisecond equal to the number of milliseconds since the PerformanceTiming.navigationStart property and the call to the method (source).
The example MDN provides is:
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
A function you could use to test the performance of a specific short piece of code multiple times, you could use the following:
/**
* Finds the performance for a given function
* function fn the function to be executed
* int n the amount of times to repeat
* return array [time elapsed for n iterations, average execution frequency (executions per second)]
*/
function getPerf(fn, n) {
var t0, t1;
t0 = performance.now();
for (var i = 0; i < n; i++) {
fn(i)
}
t1 = performance.now();
return [t1 - t0, repeat * 1000 / (t1 - t0)];
}
Which returns the amount of time a single execution of fn(i)
takes in milliseconds, and the frequency of execution (executions per second). The higher the n
value, the more precision this has, but the longer it takes to test. The argument i
can be included in the function to be tested, which contains the current iteration of the function.
回答2:
You may be looking for console.time
. See https://developer.mozilla.org/en-US/docs/Web/API/console?&redirectslug=DOM%2Fconsole#Timers.
回答3:
You should use jsPerf to get statistically significant results. Due to the various JIT systems involved in browsers, performance results can vary a lot, so jsPerf or the Benchmarking.js library it uses will run your code as many times as it needs to get good results. But note that if a function is running in just a few nanoseconds worrying about its performance is almost always unnecessary.
回答4:
You could try the profiling function built-into browser:
- https://developers.google.com/chrome-developer-tools/docs/cpu-profiling
- http://msdn.microsoft.com/en-us/library/ie/gg699341(v=vs.85).aspx
They are rich-feature and can be used out of the box without writing a single line of code
回答5:
You can use the Developer Tools Script Profiler of Internet explorer. I am sure there is a similar tool for Chrome and Firefox too. It will give you in milliseconds. But if the time taken is less than a millisecond then I think it will show in nanoseconds too.
来源:https://stackoverflow.com/questions/20821973/what-is-the-most-accurate-way-to-test-the-computation-speed-of-a-function-in-jav