Golang : How to profile or log time spend on execution?
Being able to calculate how long it takes to execute a routine or function is crucial in optimizing a program(this is also known as profiling a program). The time taken to execute a routine can help developers to determine where is the bottleneck and introduce better algorithm or use faster packages to achieve the desire result.
In this tutorial, we will explore how to calculate time spend on executing a routine or function in Golang.
The algorithm is simple :
First, take a snapshot of the time before execution and after execution. Then calculate the difference.
For example :
package main
import (
"fmt"
"log"
"time"
)
func main() {
t1 := time.Now()
fmt.Println("Do something...")
t2 := time.Now()
log.Printf("[Do something] takes about %v\n", t2.Sub(t1))
}
Sample output :
Do something...
2015/03/30 10:24:52 [Do something] takes about 36.466µs
Do something...
2015/03/30 10:24:54 [Do something] takes about 36.193µs
another example for web GET operation. This must take into account of your Internet connection speed as well.
func indexHandler(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
fmt.Fprintf(w, "Hello World!")
t2 := time.Now()
log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
}
func main() {
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":8080", nil)
}
Sample output :
[GET] / 1.1ms
[GET] /contact 2.08ms
IF you need better and detailed analysis on your Golang program. Please read up the official Golang's blog on profiling http://blog.golang.org/profiling-go-programs
Reference :
See also : Golang : Logging with logrus
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+50.8k Golang : Check if item is in slice/array
+21.8k Golang : Repeat a character by multiple of x factor
+10.9k Golang : How to use if, eq and print properly in html template
+5k Golang : How to deal with configuration data?
+5.1k Golang : Get S3 or CloudFront object or file information
+13k Golang : Verify token from Google Authenticator App
+10.9k Golang : Find age or leap age from date of birth example
+25.8k Golang : Convert(cast) string to uint8 type and back to string
+10.5k Golang : Sieve of Eratosthenes algorithm
+10.4k Golang : Get UDP client IP address and differentiate clients by port number
+12.6k Golang : Handle or parse date string with Z suffix(RFC3339) example
+8.3k Android Studio : Image button and button example