Measure execution times in Javascript

· Björn-Eric's Developer notes


Using console.time #

 1console.time('Looping')
 2for (let step = 0; step < 100.000; step++) {
 3  // Do something 100 000 times
 4}
 5
 6console.timeLog('Looping') // Log out current time
 7
 8for (let step = 0; step < 100.000; step++) {
 9  // Do something 100 000 more times
10}
11console.timeEnd('Looping')
12// output: Looping: 0.09716796875 ms

using performance.now #

In the next example we could use new Date() but that would not give us the ms granularity of performance.now

 1const timeStart = performance.now()
 2for (let step = 0; step < 100000000; step++) {
 3  // Do something 100 000 times
 4}
 5const timeIntermediate = performance.now()
 6
 7console.log(`Intermediate time ${timeIntermediate - timeStart} ms`)
 8
 9for (let step = 0; step < 100000000; step++) {
10  // Do something 100 000 times
11}
12const timeEnd = performance.now()
13console.log(`End time ${(timeEnd - timeStart)*1000} s`)

Home