time.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. unsigned long long monotonic_us(void)
  20. {
  21. struct timespec ts;
  22. if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts))
  23. bb_error_msg_and_die("clock_gettime(MONOTONIC) failed");
  24. return ts.tv_sec * 1000000ULL + ts.tv_nsec/1000;
  25. }
  26. unsigned monotonic_sec(void)
  27. {
  28. struct timespec ts;
  29. if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts))
  30. bb_error_msg_and_die("clock_gettime(MONOTONIC) failed");
  31. return ts.tv_sec;
  32. }
  33. #else
  34. unsigned long long monotonic_us(void)
  35. {
  36. struct timeval tv;
  37. gettimeofday(&tv, NULL);
  38. return tv.tv_sec * 1000000ULL + tv.tv_usec;
  39. }
  40. unsigned monotonic_sec(void)
  41. {
  42. return time(NULL);
  43. }
  44. #endif