Util.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright (c) 2006- Facebook
  2. // Distributed under the Thrift Software License
  3. //
  4. // See accompanying file LICENSE or visit the Thrift site at:
  5. // http://developers.facebook.com/thrift/
  6. #ifndef _THRIFT_CONCURRENCY_UTIL_H_
  7. #define _THRIFT_CONCURRENCY_UTIL_H_ 1
  8. #include <config.h>
  9. #include <assert.h>
  10. #include <stddef.h>
  11. #if defined(HAVE_CLOCK_GETTIME)
  12. #include <time.h>
  13. #else // defined(HAVE_CLOCK_GETTIME)
  14. #include <sys/time.h>
  15. #endif // defined(HAVE_CLOCK_GETTIME)
  16. namespace facebook { namespace thrift { namespace concurrency {
  17. /**
  18. * Utility methods
  19. *
  20. * This class contains basic utility methods for converting time formats,
  21. * and other common platform-dependent concurrency operations.
  22. * It should not be included in API headers for other concurrency library
  23. * headers, since it will, by definition, pull in all sorts of horrid
  24. * platform dependent crap. Rather it should be inluded directly in
  25. * concurrency library implementation source.
  26. *
  27. * @author marc
  28. * @version $Id:$
  29. */
  30. class Util {
  31. static const int64_t NS_PER_S = 1000000000LL;
  32. static const int64_t MS_PER_S = 1000LL;
  33. static const int64_t NS_PER_MS = 1000000LL;
  34. public:
  35. /**
  36. * Converts timespec to milliseconds
  37. *
  38. * @param struct timespec& result
  39. * @param time or duration in milliseconds
  40. */
  41. static void toTimespec(struct timespec& result, int64_t value) {
  42. result.tv_sec = value / MS_PER_S; // ms to s
  43. result.tv_nsec = (value % MS_PER_S) * NS_PER_MS; // ms to ns
  44. }
  45. /**
  46. * Converts timespec to milliseconds
  47. */
  48. static const void toMilliseconds(int64_t& result, const struct timespec& value) {
  49. result =
  50. (value.tv_sec * MS_PER_S) +
  51. (value.tv_nsec / NS_PER_MS) +
  52. (value.tv_nsec % NS_PER_MS >= 500000 ? 1 : 0);
  53. }
  54. /**
  55. * Get current time as milliseconds from epoch
  56. */
  57. static const int64_t currentTime() {
  58. #if defined(HAVE_CLOCK_GETTIME)
  59. struct timespec now;
  60. int ret = clock_gettime(CLOCK_REALTIME, &now);
  61. assert(ret == 0);
  62. return
  63. (now.tv_sec * MS_PER_S) +
  64. (now.tv_nsec / NS_PER_MS) +
  65. (now.tv_nsec % NS_PER_MS >= 500000 ? 1 : 0) ;
  66. #elif defined(HAVE_GETTIMEOFDAY)
  67. struct timeval now;
  68. int ret = gettimeofday(&now, NULL);
  69. assert(ret == 0);
  70. return
  71. (((int64_t)now.tv_sec) * MS_PER_S) +
  72. (now.tv_usec / MS_PER_S) +
  73. (now.tv_usec % MS_PER_S >= 500 ? 1 : 0);
  74. #endif // defined(HAVE_GETTIMEDAY)
  75. }
  76. };
  77. }}} // facebook::thrift::concurrency
  78. #endif // #ifndef _THRIFT_CONCURRENCY_UTIL_H_