forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update measure-time-taken-by-function.md
- Loading branch information
Showing
1 changed file
with
6 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,14 @@ | ||
### Measure time taken by function | ||
|
||
Use `performance.now()` to get start and end time for the function, `console.log()` the time taken. | ||
Pass a callback function as the argument. | ||
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. | ||
|
||
```js | ||
const timeTaken = callback => { | ||
const t0 = performance.now(), r = callback(); | ||
console.log(performance.now() - t0); | ||
console.time('timeTaken'); | ||
const r = callback(); | ||
console.timeEnd('timeTaken'); | ||
return r; | ||
}; | ||
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console) | ||
// timeTaken(() => Math.pow(2, 10)) -> 1024 | ||
// (logged): timeTaken: 0.02099609375ms | ||
``` |