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
+6.2k Golang : Use modern ciphers only in secure connection
+4.7k Swift : Get substring with rangeOfString() function example
+4.7k Golang : Markov chains to predict probability of next state example
+12.9k Golang : Convert IP version 6 address to integer or decimal number
+10k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+4.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+5.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+10k How to test Facebook App on localhost ?
+8.2k Golang : Extract or copy items from map based on value
+25.1k Golang : Encrypt and decrypt data with AES crypto
+8.9k Golang : Translate language with language package example
+8.9k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter