typestar

Durations in Go

A Duration is a count of nanoseconds with units in the literal.

func durations() []string {
    timeout := 1500 * time.Millisecond
    budget := 2 * time.Minute

    started := time.Now().Add(-90 * time.Second)
    elapsed := time.Since(started)

    return []string{
        timeout.String(),
        fmt.Sprintf("%.1f", timeout.Seconds()),
        budget.String(),
        elapsed.Round(time.Second).String(),
        (budget - elapsed).Truncate(time.Second).String(),
    }
}

How it works

  1. Multiply by a unit constant: 5 * time.Second.
  2. Since and Sub return Durations you can round.
  3. Truncate and Round control how it prints.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
350
Tokens
109
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 2 of 2 in Time, step 5 of 26 in Standard library & project layout.

← Previous Next →