- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to measure the execution time in Golang?
In Go, we have a package named time that is present in Go's standard library. This time package contains different useful functions that we can use to calculate the time taken by a code block or even a function in Go.
The most widely used functions are time.Sleep(), time.Since() and time.Now(). In this article, we will see how to use all these functions.
Let's first consider a very basic example where we will use all these functions.
Example 1
Consider the code shown below.
package main import ( "fmt" "time" ) func main() { fmt.Println("Measuring time in Go") start := time.Now() for idx := 0; idx < 10; idx++ { time.Sleep(751 * time.Millisecond) } timeElapsed := time.Since(start) fmt.Printf("The `for` loop took %s", timeElapsed) }
In the above code,
We are using time.Now() function first, which will provide us the exact time at that moment,
Then we are simply making the program to wait with the help of time.Sleep() function.
Finally, to get the actual time taken by the for loop, we pass the result that we got from time.Now() function to time.Since() function and we have our result.
Output
If we run the command go run main.go on the above code, then we will have the following output in the terminal.
Measuring time in Go The `for` loop took 7.512026652s
We can also use a different pattern, where we will use the same functions and a deferred function as well.
Example 2
Consider the code shown below.
package main import ( "fmt" "time" ) func timeElapsed() func() { start := time.Now() return func() { timeElapsed := time.Since(start) fmt.Println("This function took", timeElapsed, "time") } } func main() { defer timeElapsed()() time.Sleep(time.Second * 2) }
Output
If we run the command go run main.go on the above code, then we will have the following output in the terminal.
This function took 2.000122676s time