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
+4.5k MariaDB/MySQL : Form select statement or search query with Chinese characters
+5.9k Linux/Unix : Commands that you need to be careful about
+25.4k Golang : missing Mercurial command
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+17.7k Golang : How to log each HTTP request to your web server?
+38.8k Golang : How to iterate over a []string(array)
+4.9k Golang : Print instead of building pyramids
+5.9k Golang : Extract XML attribute data with attr field tag example
+14.3k Golang : How to get URL port?
+7.3k SSL : How to check if current certificate is sha1 or sha2 from command line
+33.3k Golang : How to check if slice or array is empty?
+31.7k Golang : Validate email address with regular expression