gettime.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. htop - generic/gettime.c
  3. (C) 2021 htop dev team
  4. Released under the GNU GPLv2+, see the COPYING file
  5. in the source distribution for its full text.
  6. */
  7. #include "config.h" // IWYU pragma: keep
  8. #include "generic/gettime.h"
  9. #include <string.h>
  10. #include <time.h>
  11. void Generic_gettime_realtime(struct timeval* tvp, uint64_t* msec) {
  12. #if defined(HAVE_CLOCK_GETTIME)
  13. struct timespec ts;
  14. if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
  15. tvp->tv_sec = ts.tv_sec;
  16. tvp->tv_usec = ts.tv_nsec / 1000;
  17. *msec = ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000);
  18. } else {
  19. memset(tvp, 0, sizeof(struct timeval));
  20. *msec = 0;
  21. }
  22. #else /* lower resolution gettimeofday(2) is always available */
  23. struct timeval tv;
  24. if (gettimeofday(&tv, NULL) == 0) {
  25. *tvp = tv; /* struct copy */
  26. *msec = ((uint64_t)tv.tv_sec * 1000) + ((uint64_t)tv.tv_usec / 1000);
  27. } else {
  28. memset(tvp, 0, sizeof(struct timeval));
  29. *msec = 0;
  30. }
  31. #endif
  32. }
  33. void Generic_gettime_monotonic(uint64_t* msec) {
  34. #if defined(HAVE_CLOCK_GETTIME)
  35. struct timespec ts;
  36. if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
  37. *msec = ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000);
  38. else
  39. *msec = 0;
  40. #else /* lower resolution gettimeofday() should be always available */
  41. struct timeval tv;
  42. if (gettimeofday(&tv, NULL) == 0)
  43. *msec = ((uint64_t)tv.tv_sec * 1000) + ((uint64_t)tv.tv_usec / 1000);
  44. else
  45. *msec = 0;
  46. #endif
  47. }