Go

time.Since — Easy Benchmark Timing

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`time.Since(start)` is shorthand for `time.Now().Sub(start)`. Pair with `defer` for a quick "how long did this function take?" measurement.
Go
Raw
package main

import (
    "fmt"
    "log"
    "time"
)

// Decorator pattern: log how long a function took
func timeIt(name string) func() {
    start := time.Now()
    return func() {
        log.Printf("%s took %s", name, time.Since(start))
    }
}

func slowOperation() {
    defer timeIt("slowOperation")()             // note the double () — invokes returned func
    time.Sleep(150 * time.Millisecond)
}

func main() {
    slowOperation()       // slowOperation took 150.3ms

    // One-liner inline
    start := time.Now()
    sum := 0
    for i := 0; i < 1_000_000; i++ { sum += i }
    fmt.Printf("sum=%d in %s\n", sum, time.Since(start))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.