Go: Measure execution time
Measure a piece of code
start := time.Now()
…Code to measure elapsed time of…
duration := time.Since(start)
// Formatted string, such as "2h3m0.5s" or "4.503μs"
fmt.Println(duration)
// Nanoseconds as int64
fmt.Println(duration.Nanoseconds())Measure a function call
You can track the execution time of a complete function call with this one-liner, which logs the result to the standard error stream.
func foo() {
        defer duration(track("foo"))
        // Code to measure
}The helper functions track and duration are defined as
func track(msg string) (string, time.Time) {
        return msg, time.Now()
}
func duration(msg string, start time.Time) {
        log.Printf("%v: %v\n", msg, time.Since(start))
}Benchmarks
The testing package has support for benchmarking that can be used to examine the performance of your code.
Comments
          Be the first to comment!