We can find the time taken to execute a function by using:
Date.now()
objectconsole.time
and console.timeEnd()
performance.now()
functionDate.now()
object We use the Date.now()
method to get the current time in milliseconds. The method helps us get the time before and after executing a function. We find the difference between the time after executing the function and the time before executing the function. This will result in the time taken to execute the function.
function test(){ for(let i = 0; i < 1000000000; i++){ } } let start = Date.now(); test(); let timeTaken = Date.now() - start; console.log("Total time taken : " + timeTaken + " milliseconds");
In the above code,
test
with a for
loop.start
.test
method.test
function by subtracting the current time from the start
time, which we will store before executing the function. test
function.console.time
and console.timeEnd()
We call the console.time()
to initiate a timer with a name. We call the console.timeEnd()
to stop the timer. This is used to get the time taken to execute a function.
function test(){ for(let i = 0; i < 1000000000; i++){ } } console.time("test_timer"); test(); console.timeEnd("test_timer");
In the above code:
test
with a for
loop.console.time
method with test_timer
as an argument. This will start the timer with test_timer
as the label.test
method.console.timeEnd
method for the label test_timer
. This will stop the timer and print the number of milliseconds between the call of console.time
and console.timeEnd
.performace.now
The performance.now
method returns the time passed (Read about time origin here). This method returns the time as floating-point numbers with up to microsecond precision.
In the above code:
test
with a for
loop.performance.now
method. This will return the elapsed time since the time origin. We store this value in the start
variable.test
method.performance.now
method to get the current elapsed time since the time origin. We subtract this value from the value obtained at the start. This will give the time taken to execute the test
function.test
function.The
performance.now
method is the most efficient way to calculate the execution time because we can calculate the execution time with microsecond precision.
RELATED TAGS
CONTRIBUTOR
View all Courses