Skip to content

Golang: Easy Way to Measuring Execution Time (Elapsed Time)

Do you want to measure the execution time of a piece of code in Golang? Yes, there is a very simple solution using the Since function from the standard time package.

// Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).
func time.Since(t time.Time) time.Duration

Working example:

package main

import (
	"fmt"
	"time"
)

func main() {
	// Create a variable to store the start time
	t := time.Now()

	// Your code to measure the execution time
	for i := 0; i < 10; i++ {
		fmt.Println(i)
	}

	// Print the elapsed time 
	fmt.Println("elapsed time", time.Since(t))
}

Leave a Reply

Your email address will not be published. Required fields are marked *