Ignore:
Timestamp:
Jul 14, 2014, 8:37:03 PM (11 years ago)
Author:
Frederik Heber <heber@…>
Children:
ef9dff6
Parents:
e93bfe
git-author:
Frederik Heber <heber@…> (06/18/14 08:14:25)
git-committer:
Frederik Heber <heber@…> (07/14/14 20:37:03)
Message:

FIX: Chronos is now working correctly, no more negative times.

  • extracted difference calculator into static function, making it thus accessible to unit testing.
  • kudos to Saskia Metzler for inspiring the test.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/Helpers/Chronos.cpp

    re93bfe rca940b  
    102102}
    103103
     104double Chronos::calculateCorrectTimeDifference(
     105    const sec_ncsec_t &_time1,
     106    const sec_ncsec_t &_time2)
     107{
     108        double currenttime = 0.;
     109  if (_time1.second < _time2.second)
     110                currenttime = (_time1.first - _time2.first - 1)
     111                        + (1e9 + _time1.second - _time2.second) * 1.e-9;
     112  else
     113                currenttime = (_time1.first - _time2.first)
     114                        + (_time1.second - _time2.second) * 1.e-9;
     115  return currenttime;
     116}
     117
    104118double Chronos::getCurrentTime() const
    105119{
     
    108122  timespec time1;
    109123  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
    110   double currenttime;
    111   if (time1.tv_nsec < basetime.tv_nsec)
    112     currenttime = (time1.tv_sec - basetime.tv_sec - 1)
    113         + (basetime.tv_nsec - time1.tv_nsec) * 1.e-9;
    114   else
    115     currenttime = (time1.tv_sec - basetime.tv_sec)
    116         + (time1.tv_nsec - basetime.tv_nsec) * 1.e-9;
     124  double currenttime = calculateCorrectTimeDifference(
     125                  std::make_pair( time1.tv_sec, time1.tv_nsec),
     126                  std::make_pair( basetime.tv_sec, basetime.tv_nsec)
     127                  );
    117128#else
    118129#ifdef HAVE_SYS_TIME_H
     
    121132  // gettimeofday gives microseconds accuracy
    122133  gettimeofday(&time1, &timezone1);
    123   double currenttime;
    124   if (time1.tv_usec < basetime.tv_usec)
    125     currenttime = (time1.tv_sec - basetime.tv_sec - 1)
    126         + (basetime.tv_usec - time1.tv_usec) * 1.e-6;
    127   else
    128     currenttime = (time1.tv_sec - basetime.tv_sec)
    129         + (time1.tv_usec - basetime.tv_usec) * 1.e-6;
     134  double currenttime = calculateCorrectTimeDifference(
     135      std::make_pair( time1.tv_sec, time1.tv_usec),
     136                  std::make_pair( basetime.tv_sec, basetime.tv_usec)
     137                  );
    130138#else
    131139#ifdef HAVE_SYS_TIMES_H
    132140  // clock is only accurate up to milliseconds
    133141  struct tms *buffer = new tms;
    134   double currenttime;
    135142  if (times(buffer) != (clock_t)(-1))
    136143    currenttime =
Note: See TracChangeset for help on using the changeset viewer.