timeutil.go 702 B

123456789101112131415161718192021222324252627
  1. // Copyright (C) 2025 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package timeutil
  7. import (
  8. "sync/atomic"
  9. "time"
  10. )
  11. var prevNanos atomic.Int64
  12. // StrictlyMonotonicNanos returns the current time in Unix nanoseconds.
  13. // Guaranteed to strictly increase for each call, regardless of the
  14. // underlying OS timer resolution or clock jumps.
  15. func StrictlyMonotonicNanos() int64 {
  16. for {
  17. old := prevNanos.Load()
  18. now := max(time.Now().UnixNano(), old+1)
  19. if prevNanos.CompareAndSwap(old, now) {
  20. return now
  21. }
  22. }
  23. }