In this shot, we will learn how to calculate the execution time for a function in golang.
We will use the defer
statement to execute a function right before the main()
function returns.
We will follow the below approach:
We will create a function where at first we will capture the present time, and
We will return an anonymous function which will print the time difference,
Since we don’t want to print the time difference when it is called, so we will call this function with defer
, then the anonymous function will execute at a later time, that is when the surrounding function returns.
Here we will use a surrounding function as main()
function. It means the anonymous function will execute right before the main()
function returns.
Let us take a look at an example.
In the following example, we will create a function getExecutionDuration()
to get execution duration. This function returns a function that prints the time difference, we will make it execute at a later period of time, using defer statement before getExecutionDuration()
call.
The returned function will execute right before the main()
function returns. So it will calculate how much duration the main()
took to execute.
package main//import packagesimport("fmt""time")//program execution starts herefunc main() {//deferred statementdefer getExecutionDuration()()//make the program to sleep for 3 secondstime.Sleep(time.Second * 3)}//function to calculate time differencefunc getExecutionDuration() func() {//get time when execution startedstart := time.Now()return func() {//executes right before main function returnsfmt.Println(time.Since(start))}}
In the above code snippet,
fmt
, which is used to format the input and output.time
, which contains functions like Now(), sleep(), etc…main()
function in golang.getExecutionDuration()()
using the defer statement, the second ()
is used to call the returned function.3
seconds to show you the clear difference in execution time.getExecutionDuration()
.
getExecutionDuration()
is executed.main()
function.main()
function returns.