Code snippets with tests and testable examples for the Go programming language

How to measure the execution time of a function

Snippets Index - Run code on Go playground - Edit

// This example demonstrates simple execution time calculation
// If you need a detailed report on a function's performance
// you should use Go benchmark functions
package main

import (

func f() {
	// first we calculate the exact time the function
	// started the execution
	start := time.Now()
	// Then we calculate the execution time duration
	// inside a deferred function, since it will be execute after f() returns
	defer func(start time.Time) {
		dur := time.Since(start)
		fmt.Printf("f() took %0.0f to execute", dur.Seconds())
	// pause the execution for 2 seconds
	time.Sleep(2 * time.Second)

func Example() {
	// Output:
	// f() took 2 to execute

by psampaz - source code - comment below or here