How to Measure Time Taken by a Function to Execute

In this snippet, we will suggest some methods that will show the way you can calculate the time which is taken by a function to execute in milliseconds.

performance.now()

The now()method of the performance interface will return a high-resolution timestamp when it is invoked during the work.

let t1 = performance.now();
// Get the end time and the compute elapsed milliseconds.
let t2 = performance.now();
let elapsed = t2 - t1; 
// Write the elapsed time to the browser title bar.
time = elapsed + " ms";
console.log(time);

console.time()

The call to console.time() starts a timer, which is later stopped by console.timeEnd(). The timer names passed to both function calls must match in order to measure.

let output = "";
// Start timing now
console.time("somename");
for (let i = 1; i <= 1e6; i++) {
  output += i;
}
// ... and stop.
console.timeEnd("somename");

getTime()

The getTime() method will return the number of milliseconds. The following script takes some milliseconds to execute:

let output = "";
// Remember started
let start = new Date().getTime();
for (let i = 1; i <= 1e6; i++) {
  output += i;
}
// Remember finished
let end = new Date().getTime();
// Now calculate and output the difference
console.log(end - start);

The performance.now() Method

The performance.now() method returns a DOMHighResTimeStamp measured in milliseconds. The time can be tracked by getting the start time before the function and end time after the function and then subtracting both. This elapses the time for the function.

The console.time() Method

The console.time() method starts a timer to track the length of an operation. Each timer has a unique name and may have up to 10,000 timers running on a given page. When the console.timeEnd() is called with the same name, the browser outputs the time in milliseconds that was elapsed since the timer started.

The getTime() Method

The getTime() method returns the number of milliseconds since the Unix Epoch. This method is used to assign a date and time to another Date object. Subtracting two subsequent getTime() calls on newly created Date objects, give the time span between these two calls. This can be used to track the executing time of operations.

Do you find this helpful?

Related articles