summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/utils/timer.cpp43
-rw-r--r--src/utils/timer.hpp13
2 files changed, 51 insertions, 5 deletions
diff --git a/src/utils/timer.cpp b/src/utils/timer.cpp
index 433fcb26..966178be 100644
--- a/src/utils/timer.cpp
+++ b/src/utils/timer.cpp
@@ -15,9 +15,13 @@
* limitations under the License.
*/
+#include <stdlib.h>
+
#include "timer.hpp"
-long long int systemTimeMs()
+#define MS_PER_SECOND 1000
+
+long long int system_time_ms()
{
struct timeb t_msec;
long long int timestamp_msec;
@@ -30,7 +34,40 @@ long long int systemTimeMs()
return timestamp_msec;
}
-
frequency_clock_t::frequency_clock_t()
: frequency_{0.0}, last_tick_{0}, time_function_{nullptr}
-{} \ No newline at end of file
+{}
+
+
+frequency_clock_t::frequency_clock_t(float frequency)
+ : frequency_{frequency}, last_tick_{0}, time_function_{nullptr}
+{}
+
+/// @brief Return the period in ms given the frequency in hertz.
+float frequency_clock_t::frequency_to_period(float frequency)
+{
+ return 1 / frequency * MS_PER_SECOND;
+}
+
+bool frequency_clock_t::started()
+{
+ return last_tick_ != 0;
+}
+
+time_function_t frequency_clock_t::get_time_function()
+{
+ return time_function_ != nullptr ? time_function_ : system_time_ms;
+}
+
+bool frequency_clock_t::elapsed(bool stagger)
+{
+ float period = frequency_to_period(frequency_);
+ float elapsed_time = 0;
+ if(!started() && stagger)
+ last_tick_ = get_time_function()() - (rand() % int(period));
+ else
+ // Make sure it ticks the the first call to conditionalTick(...)
+ elapsed_time = !started() ? period : get_time_function()() - last_tick_;
+
+ return frequency_ == 0 || elapsed_time >= period;
+}
diff --git a/src/utils/timer.hpp b/src/utils/timer.hpp
index a3cbecd6..8037b85d 100644
--- a/src/utils/timer.hpp
+++ b/src/utils/timer.hpp
@@ -24,7 +24,10 @@
*
* @return long long int epoch in milliseconds
*/
-typedef long long int (*TimeFunction)();
+typedef long long int (*time_function_t)();
+
+
+long long int system_time_ms();
/**
* @class frequency_clock_t
@@ -43,8 +46,14 @@ class frequency_clock_t
private:
float frequency_;
unsigned long last_tick_;
- TimeFunction time_function_;
+ time_function_t time_function_;
public:
frequency_clock_t();
+ frequency_clock_t(float frequency);
+
+ static float frequency_to_period(float frequency);
+ bool started();
+ time_function_t get_time_function();
+ bool elapsed(bool stagger);
}; \ No newline at end of file