Golang : Measure execution time for a function
Ok, this is another way to measure execution time of a Golang function. This method uses defer
and produce a footer to be included at the bottom of a web page. Nothing special, just another way.
Here you go!
package main
import (
"net/http"
"time"
)
func measureExecutionTime(startTime time.Time, w http.ResponseWriter, functionName string) {
timeTaken := time.Since(startTime)
footer := functionName + " took " + timeTaken.String() + " to complete. "
w.Write([]byte(footer))
}
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
// measure our function execution time
// and put the result at the footer
defer measureExecutionTime(time.Now(), w, "SayHelloWorld")
html := `<!DOCTYPE html><html><body>Hello World<br><br></body></html>`
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", mux)
}
Run the code above and point your browser to http://localhost:8080 and you should see this output(example):
Hello World
SayHelloWorld took 3.165µs to complete.
See also : Golang : Measure http.Get() execution time
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
+21.6k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+15k Golang : How to check if IP address is in range
+14k Golang : syscall.Socket example
+7.4k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+5.3k How to check with curl if my website or the asset is gzipped ?
+7.6k Golang : get the current working directory of a running program
+5.9k Golang : Experimenting with the Rejang script
+11.4k Golang : Change date format to yyyy-mm-dd
+4.5k MariaDB/MySQL : How to get version information
+18.4k Golang : Write file with io.WriteString
+6.9k Golang : Find the shortest line of text example
+4.5k Javascript : Access JSON data example