How do I measure durations and timeouts in Go?

In Go, measuring durations and implementing timeouts can be efficiently done using the time package. The package provides various tools to work with time, including the ability to set timeouts for operations and measure the duration of code execution.

Go, Golang, duration, timeout, time package, measuring time, Go programming

This article explains how to measure durations and implement timeouts in Go, making it easier for developers to time their functions and manage operations that may take too long.


package main

import (
    "fmt"
    "time"
)

func main() {
    // Measuring duration
    start := time.Now()
    
    // Simulating a long operation
    time.Sleep(2 * time.Second)
    
    duration := time.Since(start)
    fmt.Printf("Operation took %s\n", duration)

    // Implementing a timeout
    timeout := time.After(1 * time.Second)
    done := make(chan bool)

    go func() {
        // Simulating a long operation
        time.Sleep(2 * time.Second)
        done <- true
    }()

    select {
    case <-done:
        fmt.Println("Operation completed")
    case <-timeout:
        fmt.Println("Operation timed out")
    }
}
    

Go Golang duration timeout time package measuring time Go programming