time.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 2007 Denys Vlasenko
  6. *
  7. * Licensed under GPL version 2, see file LICENSE in this tarball for details.
  8. */
  9. #include "libbb.h"
  10. #if ENABLE_MONOTONIC_SYSCALL
  11. #include <sys/syscall.h>
  12. /* Old glibc (< 2.3.4) does not provide this constant. We use syscall
  13. * directly so this definition is safe. */
  14. #ifndef CLOCK_MONOTONIC
  15. #define CLOCK_MONOTONIC 1
  16. #endif
  17. /* libc has incredibly messy way of doing this,
  18. * typically requiring -lrt. We just skip all this mess */
  19. static void get_mono(struct timespec *ts)
  20. {
  21. if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, ts))
  22. bb_error_msg_and_die("clock_gettime(MONOTONIC) failed");
  23. }
  24. unsigned long long FAST_FUNC monotonic_ns(void)
  25. {
  26. struct timespec ts;
  27. get_mono(&ts);
  28. return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
  29. }
  30. unsigned long long FAST_FUNC monotonic_us(void)
  31. {
  32. struct timespec ts;
  33. get_mono(&ts);
  34. return ts.tv_sec * 1000000ULL + ts.tv_nsec/1000;
  35. }
  36. unsigned FAST_FUNC monotonic_sec(void)
  37. {
  38. struct timespec ts;
  39. get_mono(&ts);
  40. return ts.tv_sec;
  41. }
  42. #else
  43. unsigned long long FAST_FUNC monotonic_ns(void)
  44. {
  45. struct timeval tv;
  46. gettimeofday(&tv, NULL);
  47. return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
  48. }
  49. unsigned long long FAST_FUNC monotonic_us(void)
  50. {
  51. struct timeval tv;
  52. gettimeofday(&tv, NULL);
  53. return tv.tv_sec * 1000000ULL + tv.tv_usec;
  54. }
  55. unsigned FAST_FUNC monotonic_sec(void)
  56. {
  57. return time(NULL);
  58. }
  59. #endif