Skip to content

Commit

Permalink
Merge pull request #49 from sy-c/master
Browse files Browse the repository at this point in the history
Timer::increment()
  • Loading branch information
sy-c authored Oct 5, 2023
2 parents 51f9c7e + 1d2bb2a commit e7afeea
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
4 changes: 3 additions & 1 deletion include/Common/Timer.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ class Timer
/// Reset timer by adding timeout value to starting time value.
/// Usefull when called in loops, prevents loosing time elapsed after previous timeout.
/// (e.g.: to implement timeout every 1 second without drift in time)
void increment();
/// If ensureFuture is true, value is incremented until next occurence is in the future (and only if timeout has occured already),
/// to avoid possibly several successive immediate timeouts again when multiple timeout periods have been missed.
void increment(bool ensureFuture = false);

/// Check if time elapsed since timer reset (or last increment set) is bigger than timeout value set.
/// \return Returns 1 if timeout, 0 otherwise.
Expand Down
13 changes: 10 additions & 3 deletions src/Timer.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,17 @@ void Timer::reset(int timeout)
tmax = timeout / 1000000.0;
}

void Timer::increment()
void Timer::increment(bool ensureFuture)
{
t0 += std::chrono::microseconds((int)(tmax * 1000000.0));
if (ensureFuture) {
double tnext = getRemainingTime();
if ((tnext <= 0) && (tmax > 0)) {
int n = (int)(1 - (tnext / tmax));
t0 += std::chrono::microseconds((int)(n * tmax * 1000000.0));
}
} else {
t0 += std::chrono::microseconds((int)(tmax * 1000000.0));
}
}

int Timer::isTimeout()
Expand All @@ -64,4 +72,3 @@ double Timer::getRemainingTime()

} // namespace Common
} // namespace AliceO2

18 changes: 18 additions & 0 deletions test/testTimer.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ BOOST_AUTO_TEST_CASE(timer_test)
success = 1;
}

// test increment
printf("\nTest increment (ensureFuture=0)\n");
// this should blindly increase by fixed amount of time
t.reset(100000);
usleep(350000);
for (int i = 1; i <= 5; i++) {
printf("iteration %d : timeout = %d timeRemaining = %.2fs\n", i, (int)t.isTimeout(), t.getRemainingTime());
t.increment(0);
}
printf("\nTest increment (ensureFuture=1)\n");
// this should update timeout to next occurence, with respect to start and given period
t.reset(100000);
usleep(250000);
for (int i = 1; i <= 5; i++) {
printf("iteration %d : timeout = %d timeRemaining = %.2fs\n", i, (int)t.isTimeout(), t.getRemainingTime());
t.increment(1);
}

BOOST_CHECK_EQUAL(success, 1);
}

0 comments on commit e7afeea

Please sign in to comment.