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")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?