From cc7ffac297959cdf4cf7ded6ba84b48b04d427e9 Mon Sep 17 00:00:00 2001 From: Thulinma Date: Mon, 4 Aug 2014 15:57:49 +0200 Subject: [PATCH] Added Util::wait as guaranteed-time Util::sleep implementation. --- lib/timing.cpp | 24 ++++++++++++++++++++++++ lib/timing.h | 3 ++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/timing.cpp b/lib/timing.cpp index de51e3e1..3d7673a1 100644 --- a/lib/timing.cpp +++ b/lib/timing.cpp @@ -23,6 +23,30 @@ void clock_gettime(int ign, struct timespec * ts) { #endif /// Sleeps for the indicated amount of milliseconds or longer. +/// Will not sleep if ms is negative. +/// Will not sleep for longer than 10 minutes (600000ms). +/// If interrupted by signal, resumes sleep until at least ms milliseconds have passed. +/// Can be slightly off (in positive direction only) depending on OS accuracy. +void Util::wait(int ms){ + if (ms < 0) { + return; + } + if (ms > 600000) { + ms = 600000; + } + long long int start = getMS(); + long long int now = start; + while (now < start+ms){ + sleep(start+ms-now); + now = getMS(); + } +} + +/// Sleeps for roughly the indicated amount of milliseconds. +/// Will not sleep if ms is negative. +/// Will not sleep for longer than 100 seconds (100000ms). +/// Can be interrupted early by a signal, no guarantee of minimum sleep time. +/// Can be slightly off depending on OS accuracy. void Util::sleep(int ms) { if (ms < 0) { return; diff --git a/lib/timing.h b/lib/timing.h index e2a4313b..0c027a45 100644 --- a/lib/timing.h +++ b/lib/timing.h @@ -4,7 +4,8 @@ #pragma once namespace Util { - void sleep(int ms); ///< Sleeps for the indicated amount of milliseconds or longer. + void wait(int ms); ///< Sleeps for the indicated amount of milliseconds or longer. + void sleep(int ms); ///< Sleeps for roughly the indicated amount of milliseconds. long long int getMS(); ///< Gets the current time in milliseconds. long long int bootSecs(); ///< Gets the current system uptime in seconds. long long unsigned int getMicros();///