In this article, we will explore some techniques for measuring your code. Measuring execution time is essential, especially for complex or performance-critical operations.
Using console.time()
and console.timeEnd()
One of the simplest ways to measure the execution of your code is by using console.time()
and console.timeEnd()
.
console.time()
is a JavaScript method that starts a timer. By starting a timer, you can calculate how long it takes for a program to execute.
The syntax looks like this:
console.time(label)
This method takes a single optional parameter called label
, which specifies the name of the timer. Naming the timer is important, especially when testing various parts of the code with different timers.
console.timeEnd()
is the method used to stop the timer. It also takes label
as a parameter. When calling console.timeEnd()
, you should use the same label that was used with console.time()
.
For example, suppose we have a for
loop and we need to measure the time taken to complete the loop. We would do something like this:
console.time('loop')
for(let i = 0; i < 10000; i++) {
console.log(i)
}
console.timeEnd('loop')
Here is a truncated output
9998
9999
loop: 95.798ms
Timing with Performance.now()
If you need a more accurate representation of the time taken to execute an operation, use performance.now()
. This method provides a high-resolution timestamp in milliseconds than Date.now()
.
Here's an example:
const start = performance.now();
for(let i = 0; i < 10000; i++) {
// console.log(i)
}
const end = performance.now();
console.log(`Time elaped ${end - start} milliseconds.`);
Summary
If you need a higher precision, always opt for performance.now() especially for performance-critical tasks.
console.time()
and console.timeEnd()
are useful for quick debugging but may lack precision.
Ready to dive into React?
EchoAPI has significantly reduced the time I spend on API testing. It’s efficient and allows me to focus on what matters most—developing great applications.