From d3f91252b0eb2e8d7d54988ed717bd2ddc55fa50 Mon Sep 17 00:00:00 2001 From: mbandic Date: Mon, 25 Mar 2024 10:17:54 +0000 Subject: [PATCH] Change microseconds for interlan counting in timer functions --- lib/rotor.hpp | 14 ++++++++++---- test/test.cpp | 18 +++++++++++------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/lib/rotor.hpp b/lib/rotor.hpp index 4253aee..b0cc44c 100644 --- a/lib/rotor.hpp +++ b/lib/rotor.hpp @@ -22,6 +22,12 @@ int64_t rtime_ms() { .count(); } +int64_t rtime_us() { + return chrono::duration_cast(chrono::system_clock::now() + .time_since_epoch()) + .count(); +} + /** * Intern class for timer async loop */ @@ -38,7 +44,7 @@ class timer_core { * Timer constructor, receives a callback function and time */ timer_core( function _callback, int64_t _time, bool _repeat): - callback(_callback), init(rtime_ms()), time(_time), repeat(_repeat), stop(false) { + callback(_callback), init(rtime_us()), time(_time*1000), repeat(_repeat), stop(false) { } /** @@ -83,7 +89,7 @@ class rotor { else if (expired(tcores[i])) { _asyncon.put_task(tcores[i]->callback); if (tcores[i]->repeat) { - tcores[i]->init = rtime_ms(); + tcores[i]->init = rtime_us(); } else { remove(i); @@ -91,7 +97,7 @@ class rotor { } } } - this_thread::sleep_for(chrono::milliseconds(sampling)); + this_thread::sleep_for(chrono::microseconds(sampling)); } } @@ -99,7 +105,7 @@ class rotor { * The method checks whether the time event has expired */ bool expired(shared_ptr tcore) { - return rtime_ms() - tcore->init >= tcore->time; + return rtime_us() - tcore->init >= tcore->time; } /** diff --git a/test/test.cpp b/test/test.cpp index 60ae5ea..06fba99 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -65,21 +65,25 @@ int main () { */ interval( [&] () { - cout << "interval " << rtime_ms() - start << endl; - }, 200); + cout << "interval 1: " << rtime_ms() - start << endl; + }, 50); interval( [&] () { - cout << "interval " << rtime_ms() - start << endl; - }, 200); + cout << "interval 1: " << rtime_ms() - start << endl; + }, 100); interval( [&] () { - cout << "interval " << rtime_ms() - start << endl; + cout << "interval 2: " << rtime_ms() - start << endl; }, 200); + interval( [&] () { + cout << "interval 3: " << rtime_ms() - start << endl; + }, 300); + interval( [&] () { - cout << "interval " << rtime_ms() - start << endl; - }, 200); + cout << "interval 4: " << rtime_ms() - start << endl; + }, 400); // interval inter1 ([&]() { // cout << "interval prvi " << rtime_ms() - start << endl;