HighRezTimerPosix.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Util/HighRezTimer.h>
  6. #include <AnKi/Util/Assert.h>
  7. #include <sys/time.h>
  8. #include <unistd.h>
  9. #include <errno.h>
  10. #include <time.h>
  11. namespace anki {
  12. namespace {
  13. /// A dummy struct that inits the timer
  14. class StartTime
  15. {
  16. public:
  17. /// The first ticks value of the application
  18. timespec m_time;
  19. StartTime()
  20. {
  21. clock_gettime(CLOCK_MONOTONIC, &m_time);
  22. }
  23. };
  24. static StartTime g_startTime;
  25. } // namespace
  26. static U64 getNs()
  27. {
  28. U64 ticks;
  29. timespec now;
  30. clock_gettime(CLOCK_MONOTONIC, &now);
  31. ticks = U64(now.tv_sec - g_startTime.m_time.tv_sec) * 1000000000 + (now.tv_nsec - g_startTime.m_time.tv_nsec);
  32. return ticks;
  33. }
  34. void HighRezTimer::sleep(Second sec)
  35. {
  36. ANKI_ASSERT(sec >= 0.0);
  37. int wasError;
  38. U64 ns = static_cast<U64>(sec * 1e+9);
  39. struct timespec elapsed, tv;
  40. elapsed.tv_sec = ns / 1000000000;
  41. elapsed.tv_nsec = (ns % 1000000000);
  42. do
  43. {
  44. errno = 0;
  45. tv.tv_sec = elapsed.tv_sec;
  46. tv.tv_nsec = elapsed.tv_nsec;
  47. wasError = nanosleep(&tv, &elapsed);
  48. } while(wasError && (errno == EINTR));
  49. }
  50. Second HighRezTimer::getCurrentTime()
  51. {
  52. return Second(getNs()) / 1000000000.0;
  53. }
  54. U64 HighRezTimer::getCurrentTimeMs()
  55. {
  56. return getNs() * 1000000;
  57. }
  58. U64 HighRezTimer::getCurrentTimeUs()
  59. {
  60. return getNs() * 1000;
  61. }
  62. } // end namespace anki