sucycletimer.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <errno.h>
  2. #include "sucycletimer.h"
  3. /////////////////////////////////////////////////////////////////////////////
  4. CCycleTimer::CCycleTimer(unsigned int nMaxCycleIntervalMilliSec1, unsigned int nMaxCycleIntervalMilliSec2, unsigned int nMaxCycleIntervalMilliSec3) : m_nMaxCycleNanoSec1(nMaxCycleIntervalMilliSec1 * _NSEC_PER_MSEC),
  5. m_nMaxCycleNanoSec2(nMaxCycleIntervalMilliSec2 * _NSEC_PER_MSEC),
  6. m_nMaxCycleNanoSec3(nMaxCycleIntervalMilliSec3 * _NSEC_PER_MSEC)
  7. {
  8. memset(&m_ts, 0, sizeof(m_ts));
  9. ::clock_getres(CLOCK_MONOTONIC, &m_res);
  10. }
  11. CCycleTimer::CCycleTimer(const struct timespec *pts1, const struct timespec *pts2, const struct timespec *pts3) : m_nMaxCycleNanoSec1(pts1 ? Timespec2NanoSec(*pts1) : 0),
  12. m_nMaxCycleNanoSec2(pts2 ? Timespec2NanoSec(*pts2) : 0),
  13. m_nMaxCycleNanoSec3(pts3 ? Timespec2NanoSec(*pts3) : 0)
  14. {
  15. memset(&m_ts, 0, sizeof(m_ts));
  16. ::clock_getres(CLOCK_MONOTONIC, &m_res);
  17. }
  18. CCycleTimer::~CCycleTimer(void)
  19. {
  20. }
  21. /////////////////////////////////////////////////////////////////////////////
  22. cy_time_t CCycleTimer::GetNanoTick(struct timespec *pts)
  23. {
  24. struct timespec ts;
  25. struct timespec &rts = pts ? *pts : ts;
  26. ::clock_gettime(CLOCK_MONOTONIC, &rts);
  27. return Timespec2NanoSec(rts);
  28. }
  29. cy_time_t CCycleTimer::GetNanoSecElapsed(const struct timespec *ptsComparand) const
  30. {
  31. struct timespec ts;
  32. if(!ptsComparand)
  33. {
  34. ::clock_gettime(CLOCK_MONOTONIC, &ts);
  35. ptsComparand = &ts;
  36. }
  37. return TimespecDiffNanoSec(*ptsComparand, m_ts);
  38. }
  39. int CCycleTimer::Sleep(const cy_time_t &rnMaxCycleNanoSec, bool bResumeOnIntr) const
  40. {
  41. cy_time_t nIntv;
  42. struct timespec ts, rem;
  43. ::clock_gettime(CLOCK_MONOTONIC, &ts);
  44. if((nIntv = rnMaxCycleNanoSec - GetNanoSecElapsed(&ts)) > 0)
  45. {
  46. int nRet;
  47. NanoSec2Timespec(nIntv, ts);
  48. if((nRet = ::clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &rem)))
  49. {
  50. if(bResumeOnIntr)
  51. {
  52. while(nRet == EINTR)
  53. {
  54. nRet = ::clock_nanosleep(CLOCK_MONOTONIC, 0, &rem, &rem);
  55. }
  56. }
  57. }
  58. return nRet;
  59. }
  60. return 0;
  61. }
  62. void CCycleTimer::TimespecAddSubNanoSec(struct timespec &rts, cy_time_t nNanoSec)
  63. {
  64. cy_time_t n = Timespec2NanoSec(rts) + nNanoSec;
  65. NanoSec2Timespec(n, rts);
  66. }