aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--test/timer.cc18
-rw-r--r--timer.h7
2 files changed, 25 insertions, 0 deletions
diff --git a/test/timer.cc b/test/timer.cc
index 5ac169c..3b5b5ac 100644
--- a/test/timer.cc
+++ b/test/timer.cc
@@ -1,5 +1,6 @@
#include <timer.h>
#include <unistd.h>
+#include <cassert>
#include <cstdio>
int main() {
@@ -15,6 +16,9 @@ int main() {
const timer::scoped_timer kS{t};
usleep(100 * 1000);
}
+ assert(100000 < t.as_usec() && t.as_usec() < 101000);
+ assert(100 < t.as_msec() && t.as_msec() < 101);
+ assert(0.100 < t.as_sec() && t.as_sec() < 0.101);
kShowTime();
{
@@ -22,6 +26,20 @@ int main() {
const timer::scoped_timer kS{t};
usleep(500 * 1000);
}
+ assert(600000 < t.as_usec() && t.as_usec() < 601000);
+ assert(600 < t.as_msec() && t.as_msec() < 601);
+ assert(0.600 < t.as_sec() && t.as_sec() < 0.601);
+ kShowTime();
+
+ t.reset();
+ {
+ puts("Sleep 200ms");
+ timer::scoped_timer s{t};
+ usleep(200 * 1000);
+ }
+ assert(200000 < t.as_usec() && t.as_usec() < 201000);
+ assert(200 < t.as_msec() && t.as_msec() < 201);
+ assert(0.200 < t.as_sec() && t.as_sec() < 0.201);
kShowTime();
return 0;
diff --git a/timer.h b/timer.h
index ce0e629..15e0497 100644
--- a/timer.h
+++ b/timer.h
@@ -2,6 +2,7 @@
#include <ctime>
namespace timer {
+/// A minimal Linux watch clock.
struct timer {
constexpr timer() = default;
@@ -17,6 +18,10 @@ struct timer {
(end.tv_nsec - m_start.tv_nsec);
}
+ constexpr void reset() {
+ m_nanos = 0;
+ }
+
constexpr double as_sec() const {
return as_msec() / 1000.0;
}
@@ -36,6 +41,8 @@ struct timer {
std::uint64_t m_nanos{0};
};
+/// A scoped timer to automatically start / stop a watch clock in the scope the
+/// scoped_timer lives.
struct scoped_timer {
explicit scoped_timer(timer& t) : m_timer(t) {
m_timer.start();