xtime.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* xtime -- extended-resolution integer timestamps
  2. Copyright (C) 2005-2006, 2009-2020 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. /* Written by Paul Eggert. */
  14. #ifndef XTIME_H_
  15. #define XTIME_H_ 1
  16. #ifndef _GL_INLINE_HEADER_BEGIN
  17. #error "Please include config.h first."
  18. #endif
  19. _GL_INLINE_HEADER_BEGIN
  20. #ifndef XTIME_INLINE
  21. # define XTIME_INLINE _GL_INLINE
  22. #endif
  23. /* xtime_t is a signed type used for timestamps. It is an integer
  24. type that is a count of nanoseconds. */
  25. typedef long long int xtime_t;
  26. #define XTIME_PRECISION 1000000000
  27. #ifdef __cplusplus
  28. extern "C" {
  29. #endif
  30. /* Return an extended time value that contains S seconds and NS
  31. nanoseconds. S and NS should be nonnegative; otherwise, integer
  32. overflow can occur even if the result is in range. */
  33. XTIME_INLINE xtime_t
  34. xtime_make (xtime_t s, long int ns)
  35. {
  36. return XTIME_PRECISION * s + ns;
  37. }
  38. /* The following functions split an extended time value:
  39. T = XTIME_PRECISION * xtime_sec (T) + xtime_nsec (T)
  40. with 0 <= xtime_nsec (T) < XTIME_PRECISION. */
  41. /* Return the number of seconds in T, which must be nonnegative. */
  42. XTIME_INLINE xtime_t
  43. xtime_nonnegative_sec (xtime_t t)
  44. {
  45. return t / XTIME_PRECISION;
  46. }
  47. /* Return the number of seconds in T. */
  48. XTIME_INLINE xtime_t
  49. xtime_sec (xtime_t t)
  50. {
  51. return (t + (t < 0)) / XTIME_PRECISION - (t < 0);
  52. }
  53. /* Return the number of nanoseconds in T, which must be nonnegative. */
  54. XTIME_INLINE long int
  55. xtime_nonnegative_nsec (xtime_t t)
  56. {
  57. return t % XTIME_PRECISION;
  58. }
  59. /* Return the number of nanoseconds in T. */
  60. XTIME_INLINE long int
  61. xtime_nsec (xtime_t t)
  62. {
  63. long int ns = t % XTIME_PRECISION;
  64. if (ns < 0)
  65. ns += XTIME_PRECISION;
  66. return ns;
  67. }
  68. #ifdef __cplusplus
  69. }
  70. #endif
  71. #endif