BTime.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * @file BTime.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * System time abstraction used by {@link BReactor}.
  25. */
  26. #ifndef BADVPN_SYSTEM_BTIME_H
  27. #define BADVPN_SYSTEM_BTIME_H
  28. #ifdef BADVPN_USE_WINAPI
  29. #include <windows.h>
  30. #else
  31. #include <time.h>
  32. #endif
  33. #include <stdint.h>
  34. #include <misc/debug.h>
  35. typedef int64_t btime_t;
  36. struct _BTime_global {
  37. #ifndef NDEBUG
  38. int initialized; // initialized statically
  39. #endif
  40. #ifdef BADVPN_USE_WINAPI
  41. LARGE_INTEGER start_time;
  42. #else
  43. btime_t start_time;
  44. #endif
  45. };
  46. extern struct _BTime_global btime_global;
  47. static void BTime_Init (void)
  48. {
  49. ASSERT(!btime_global.initialized)
  50. #ifdef BADVPN_USE_WINAPI
  51. ASSERT_FORCE(QueryPerformanceCounter(&btime_global.start_time))
  52. #else
  53. struct timespec ts;
  54. ASSERT_FORCE(clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
  55. btime_global.start_time = (int64_t)ts.tv_sec * 1000 + (int64_t)ts.tv_nsec/1000000;
  56. #endif
  57. #ifndef NDEBUG
  58. btime_global.initialized = 1;
  59. #endif
  60. }
  61. static btime_t btime_gettime ()
  62. {
  63. ASSERT(btime_global.initialized)
  64. #ifdef BADVPN_USE_WINAPI
  65. LARGE_INTEGER count;
  66. LARGE_INTEGER freq;
  67. ASSERT_FORCE(QueryPerformanceCounter(&count))
  68. ASSERT_FORCE(QueryPerformanceFrequency(&freq))
  69. return (((count.QuadPart - btime_global.start_time.QuadPart) * 1000) / freq.QuadPart);
  70. #else
  71. struct timespec ts;
  72. ASSERT_FORCE(clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
  73. return (((int64_t)ts.tv_sec * 1000 + (int64_t)ts.tv_nsec/1000000) - btime_global.start_time);
  74. #endif
  75. }
  76. #endif