Update measure-time-taken-by-function.md

This commit is contained in:
atomiks
2017-12-15 08:43:47 +11:00
committed by GitHub
parent 6074aa6754
commit 94799c46d9

View File

@ -1,13 +1,14 @@
### Measure time taken by function ### Measure time taken by function
Use `performance.now()` to get start and end time for the function, `console.log()` the time taken. Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute.
Pass a callback function as the argument.
```js ```js
const timeTaken = callback => { const timeTaken = callback => {
const t0 = performance.now(), r = callback(); console.time('timeTaken');
console.log(performance.now() - t0); const r = callback();
console.timeEnd('timeTaken');
return r; return r;
}; };
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console) // timeTaken(() => Math.pow(2, 10)) -> 1024
// (logged): timeTaken: 0.02099609375ms
``` ```