timestruct.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  5. package unix
  6. // TimespecToNsec converts a Timespec value into a number of
  7. // nanoseconds since the Unix epoch.
  8. func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
  9. // NsecToTimespec takes a number of nanoseconds since the Unix epoch
  10. // and returns the corresponding Timespec value.
  11. func NsecToTimespec(nsec int64) Timespec {
  12. sec := nsec / 1e9
  13. nsec = nsec % 1e9
  14. if nsec < 0 {
  15. nsec += 1e9
  16. sec--
  17. }
  18. return setTimespec(sec, nsec)
  19. }
  20. // TimevalToNsec converts a Timeval value into a number of nanoseconds
  21. // since the Unix epoch.
  22. func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
  23. // NsecToTimeval takes a number of nanoseconds since the Unix epoch
  24. // and returns the corresponding Timeval value.
  25. func NsecToTimeval(nsec int64) Timeval {
  26. nsec += 999 // round up to microsecond
  27. usec := nsec % 1e9 / 1e3
  28. sec := nsec / 1e9
  29. if usec < 0 {
  30. usec += 1e6
  31. sec--
  32. }
  33. return setTimeval(sec, usec)
  34. }
  35. // Unix returns ts as the number of seconds and nanoseconds elapsed since the
  36. // Unix epoch.
  37. func (ts *Timespec) Unix() (sec int64, nsec int64) {
  38. return int64(ts.Sec), int64(ts.Nsec)
  39. }
  40. // Unix returns tv as the number of seconds and nanoseconds elapsed since the
  41. // Unix epoch.
  42. func (tv *Timeval) Unix() (sec int64, nsec int64) {
  43. return int64(tv.Sec), int64(tv.Usec) * 1000
  44. }
  45. // Nano returns ts as the number of nanoseconds elapsed since the Unix epoch.
  46. func (ts *Timespec) Nano() int64 {
  47. return int64(ts.Sec)*1e9 + int64(ts.Nsec)
  48. }
  49. // Nano returns tv as the number of nanoseconds elapsed since the Unix epoch.
  50. func (tv *Timeval) Nano() int64 {
  51. return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
  52. }