Go Reference ยท Time, Math and Randomness
Go time.Since() and time.Until() functions
Reference for Go time.Since and time.Until: measure how long code took, time remaining until a deadline, monotonic clocks and benchmarking caveats.
time.Since(t) returns the time.Duration that has passed since t. time.Until(t) is its mirror image: the duration remaining until t, negative if t is already in the past. Both are shorthand: Since(t) is time.Now().Sub(t) and Until(t) is t.Sub(time.Now()).
When t came from time.Now(), the calculation uses the monotonic clock, so the result is correct even if the system clock is adjusted during the measurement. That makes Since the right tool for timing code, for timeouts and for rate limiting.
start := time.Now() work() fmt.Println("took", time.Since(start))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Since(t Time) Duration func Until(t Time) Duration
| Name | Description |
|---|---|
t |
The reference moment. For correct monotonic timing it should come from time.Now(). |
Returns: a time.Duration (nanoseconds as int64). Since is positive for past times and negative for future ones; Until is the opposite.
Edge cases: durations are limited to about 292 years. If the true difference is larger, the result saturates at the maximum (1<<63 - 1) or minimum Duration instead of overflowing.
Usage notes
- Timing code: keep the start value from
time.Now(). If it has been throughtime.Parse,UTC(),Round(0)or a database, the monotonic reading is gone and the wall clock is used. - Print durations directly (
fmt.Println(d)gives1.5s,250ms,3m0s) or used.Milliseconds(),d.Seconds()as numbers. - Benchmarks: for measuring performance use
testing.B. A singleSincemeasurement is affected by caches, the scheduler and garbage collection. - Nanosecond timing is limited by the clock; on some systems the resolution is hundreds of nanoseconds or worse (Windows historically about 100 ns to 15 ms).
- Do not use
Sincefor calendar logic like "age in years"; durations know nothing about leap years or months. - Deadlines:
time.Until(deadline)is handy to pass totime.After,time.NewTimeror as a context timeout, butcontext.WithDeadlinetakes the deadlineTimeitself. - Checking expiry is
time.Now().After(expires)ortime.Until(expires) <= 0; both are fine. - A
deferthat evaluatestime.Now()at defer time, as in the first example, captures the start correctly; writingdefer log(time.Since(start))would evaluateSinceimmediately and print about zero.