Files
pip/pitimer.h

456 lines
19 KiB
C++

/*! \file pitimer.h
* \brief Timer
*/
/*
PIP - Platform Independent Primitives
Timer
Copyright (C) 2013 Ivan Pelipenko peri4ko@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PITIMER_H
#define PITIMER_H
#include <ctime>
#include <csignal>
#include "pithread.h"
#include "pistring.h"
#include "piobject.h"
typedef void (*TimerEvent)(void * , int );
class PIP_EXPORT PISystemTime {
public:
//! Contructs system time with s = ns = 0
PISystemTime() {seconds = nanoseconds = 0;}
//! Contructs system time with s = "s" and ns = "ns"
PISystemTime(long s, long ns) {seconds = s; nanoseconds = ns; checkOverflows();}
//! Contructs system time from another
PISystemTime(const PISystemTime & t) {seconds = t.seconds; nanoseconds = t.nanoseconds;}
//! Returns stored system time value in seconds
double toSeconds() const {return double(seconds) + nanoseconds / 1.e+9;}
//! Returns stored system time value in milliseconds
double toMilliseconds() const {return seconds * 1.e+3 + nanoseconds / 1.e+6;}
//! Returns stored system time value in microseconds
double toMicroseconds() const {return seconds * 1.e+6 + nanoseconds / 1.e+3;}
//! Returns stored system time value in nanoseconds
double toNanoseconds() const {return seconds * 1.e+9 + double(nanoseconds);}
//! Add to stored system time "v" seconds
PISystemTime & addSeconds(double v) {*this += fromSeconds(v); return *this;}
//! Add to stored system time "v" milliseconds
PISystemTime & addMilliseconds(double v) {*this += fromMilliseconds(v); return *this;}
//! Add to stored system time "v" microseconds
PISystemTime & addMicroseconds(double v) {*this += fromMicroseconds(v); return *this;}
//! Add to stored system time "v" nanoseconds
PISystemTime & addNanoseconds(double v) {*this += fromNanoseconds(v); return *this;}
//! Sleep for stored value. \warning Use this function to sleep for difference of system times or constructs system time.
//! If you call this function on system time returned from \a currentSystemTime() thread will be sleep almost forever.
void sleep() {piUSleep(piFloord(toMicroseconds()));} // wait self value, useful to wait some dT = (t1 - t0)
//! Returns copy of this system time with absolutely values of s and ns
PISystemTime abs() const {return PISystemTime(piAbsl(seconds), piAbsl(nanoseconds));}
//! Returns sum of this system time with "t"
PISystemTime operator +(const PISystemTime & t) {PISystemTime tt(*this); tt.seconds += t.seconds; tt.nanoseconds += t.nanoseconds; tt.checkOverflows(); return tt;}
//! Returns difference between this system time and "t"
PISystemTime operator -(const PISystemTime & t) {PISystemTime tt(*this); tt.seconds -= t.seconds; tt.nanoseconds -= t.nanoseconds; tt.checkOverflows(); return tt;}
//! Add to stored value system time "t"
PISystemTime & operator +=(const PISystemTime & t) {seconds += t.seconds; nanoseconds += t.nanoseconds; checkOverflows(); return *this;}
//! Subtract from stored value system time "t"
PISystemTime & operator -=(const PISystemTime & t) {seconds -= t.seconds; nanoseconds -= t.nanoseconds; checkOverflows(); return *this;}
//! Compare system times
bool operator ==(const PISystemTime & t) {return ((seconds == t.seconds) && (nanoseconds == t.nanoseconds));}
//! Compare system times
bool operator !=(const PISystemTime & t) {return ((seconds != t.seconds) || (nanoseconds != t.nanoseconds));}
//! Compare system times
bool operator >(const PISystemTime & t) {if (seconds == t.seconds) return nanoseconds > t.nanoseconds; return seconds > t.seconds;}
//! Compare system times
bool operator <(const PISystemTime & t) {if (seconds == t.seconds) return nanoseconds < t.nanoseconds; return seconds < t.seconds;}
//! Compare system times
bool operator >=(const PISystemTime & t) {if (seconds == t.seconds) return nanoseconds >= t.nanoseconds; return seconds >= t.seconds;}
//! Compare system times
bool operator <=(const PISystemTime & t) {if (seconds == t.seconds) return nanoseconds <= t.nanoseconds; return seconds <= t.seconds;}
//! Contructs system time from seconds "v"
static PISystemTime fromSeconds(double v) {long s = piFloord(v); return PISystemTime(s, (v - s) * 1000000000);}
//! Contructs system time from milliseconds "v"
static PISystemTime fromMilliseconds(double v) {long s = piFloord(v / 1000.); return PISystemTime(s, (v / 1000. - s) * 1000000000);}
//! Contructs system time from microseconds "v"
static PISystemTime fromMicroseconds(double v) {long s = piFloord(v / 1000000.); return PISystemTime(s, (v / 1000000. - s) * 1000000000);}
//! Contructs system time from nanoseconds "v"
static PISystemTime fromNanoseconds(double v) {long s = piFloord(v / 1000000000.); return PISystemTime(s, (v / 1000000000. - s) * 1000000000);}
//! Seconds of stored system time
long seconds;
//! Nanoseconds of stored system time
long nanoseconds;
private:
void checkOverflows() {while (nanoseconds >= 1000000000) {nanoseconds -= 1000000000; seconds++;} while (nanoseconds < 0) {nanoseconds += 1000000000; seconds--;}}
};
//! \relatesalso PICout \relatesalso PIByteArray \brief Output operator to PICout
inline PICout operator <<(PICout s, const PISystemTime & v) {s.setControl(0, true); s.space(); s << "(" << v.seconds << " s, " << v.nanoseconds << " ns)"; s.restoreControl(); return s;}
//! \relatesalso PISystemTime \relatesalso PIByteArray \brief Output operator to PIByteArray
inline PIByteArray & operator <<(PIByteArray & s, const PISystemTime & v) {s << v.seconds << v.nanoseconds; return s;}
//! \relatesalso PISystemTime \relatesalso PIByteArray \brief Input operator from PIByteArray
inline PIByteArray & operator >>(PIByteArray & s, PISystemTime & v) {s >> v.seconds >> v.nanoseconds; return s;}
struct PIP_EXPORT PITime {
PITime() {hours = minutes = seconds = milliseconds = 0;}
int milliseconds;
int seconds;
int minutes;
int hours;
PIString toString(const PIString & format = "h:mm:ss") const;
};
PIP_EXPORT bool operator ==(const PITime & t0, const PITime & t1);
PIP_EXPORT bool operator <(const PITime & t0, const PITime & t1);
PIP_EXPORT bool operator >(const PITime & t0, const PITime & t1);
inline bool operator !=(const PITime & t0, const PITime & t1) {return !(t0 == t1);}
inline bool operator <=(const PITime & t0, const PITime & t1) {return !(t0 > t1);}
inline bool operator >=(const PITime & t0, const PITime & t1) {return !(t0 < t1);}
struct PIP_EXPORT PIDate {
PIDate() {year = month = day = 0;}
int day;
int month;
int year;
PIString toString(const PIString & format = "d.MM.yyyy") const;
};
PIP_EXPORT bool operator ==(const PIDate & t0, const PIDate & t1);
PIP_EXPORT bool operator <(const PIDate & t0, const PIDate & t1);
PIP_EXPORT bool operator >(const PIDate & t0, const PIDate & t1);
inline bool operator !=(const PIDate & t0, const PIDate & t1) {return !(t0 == t1);}
inline bool operator <=(const PIDate & t0, const PIDate & t1) {return !(t0 > t1);}
inline bool operator >=(const PIDate & t0, const PIDate & t1) {return !(t0 < t1);}
struct PIP_EXPORT PIDateTime {
PIDateTime() {year = month = day = hours = minutes = seconds = 0;}
PIDateTime(const PITime & time) {year = month = day = 0; hours = time.hours; minutes = time.minutes; seconds = time.seconds; milliseconds = time.milliseconds;}
PIDateTime(const PIDate & date) {year = date.year; month = date.month; day = date.day; hours = minutes = seconds = milliseconds = 0;}
PIDateTime(const PIDate & date, const PITime & time) {year = date.year; month = date.month; day = date.day; hours = time.hours; minutes = time.minutes; seconds = time.seconds; milliseconds = time.milliseconds;}
int milliseconds;
int seconds;
int minutes;
int hours;
int day;
int month;
int year;
PIDateTime normalized() const {return PIDateTime::fromSecondSinceEpoch(toSecondSinceEpoch());}
void normalize() {*this = normalized();}
PIString toString(const PIString & format = "h:mm:ss d.MM.yyyy") const;
time_t toSecondSinceEpoch() const;
PISystemTime toSystemTime() const {return PISystemTime(int(toSecondSinceEpoch()), milliseconds * 1000000);}
void operator +=(const PIDateTime & d1) {year += d1.year; month += d1.month; day += d1.day; hours += d1.hours; minutes += d1.minutes; seconds += d1.seconds; normalize();}
void operator -=(const PIDateTime & d1) {year -= d1.year; month -= d1.month; day -= d1.day; hours -= d1.hours; minutes -= d1.minutes; seconds -= d1.seconds; normalize();}
static PIDateTime fromSecondSinceEpoch(const time_t sec);
static PIDateTime fromSystemTime(const PISystemTime & st) {PIDateTime dt = fromSecondSinceEpoch(st.seconds); dt.milliseconds = piClampi(st.nanoseconds / 1000000, 0, 999); return dt;}
};
inline PIDateTime operator +(const PIDateTime & d0, const PIDateTime & d1) {PIDateTime td = d0; td += d1; return td.normalized();}
inline PIDateTime operator -(const PIDateTime & d0, const PIDateTime & d1) {PIDateTime td = d0; td -= d1; return td.normalized();}
PIP_EXPORT bool operator ==(const PIDateTime & t0, const PIDateTime & t1);
PIP_EXPORT bool operator <(const PIDateTime & t0, const PIDateTime & t1);
PIP_EXPORT bool operator >(const PIDateTime & t0, const PIDateTime & t1);
inline bool operator !=(const PIDateTime & t0, const PIDateTime & t1) {return !(t0 == t1);}
inline bool operator <=(const PIDateTime & t0, const PIDateTime & t1) {return !(t0 > t1);}
inline bool operator >=(const PIDateTime & t0, const PIDateTime & t1) {return !(t0 < t1);}
class PIP_EXPORT PITimer
#ifndef PIP_TIMER_RT
: public PIThread
#else
: public PIObject
#endif
{
PIOBJECT(PITimer)
public:
//! \brief Constructs timer with execution function \b slot and common data \b data.
PITimer(TimerEvent slot = 0, void * data = 0, bool threaded = true);
PITimer(bool threaded);
virtual ~PITimer();
//! \brief Set custom data.
void setData(void * data_) {data = data_;}
//! \brief Set timer execution function.
void setSlot(TimerEvent slot) {ret_func = slot;}
//! \brief Returns current loop delay.
double interval() const {return interval_;}
EVENT_HANDLER0(void, reset) {
# ifdef WINDOWS
//t_st = GetCurrentTime();
pc_st = __PIQueryPerformanceCounter();
# elif defined(MAC_OS)
clock_get_time(__pi_mac_clock, &t_st);
# else
clock_gettime(0, &t_st);
# endif
}
EVENT_HANDLER1(void, start, int, msecs) {start(double(msecs));}
EVENT_HANDLER1(void, start, double, msecs);
EVENT_HANDLER2(void, deferredStart, double, interval_msecs, double, delay_msecs);
EVENT_HANDLER2(void, deferredStart, double, interval_msecs, const PIDateTime &, start_datetime);
#ifndef PIP_TIMER_RT
EVENT_HANDLER0(void, stop) {running_ = false; PIThread::stop();}
#else
EVENT_HANDLER0(void, stop);
EVENT_HANDLER0(bool, waitForFinish) {return waitForFinish(-1);}
EVENT_HANDLER1(bool, waitForFinish, int, timeout_msecs);
bool isRunning() const {return running_;}
void needLockRun(bool need) {lockRun = need;}
EVENT_HANDLER0(void, lock) {mutex_.lock();}
EVENT_HANDLER0(void, unlock) {mutex_.unlock();}
#endif
//! \brief Add frequency delimiter \b delim with optional delimiter slot \b slot.
void addDelimiter(int delim, TimerEvent slot = 0) {ret_funcs << TimerSlot(slot, delim);}
//! \brief Remove all frequency delimiters \b delim.
void removeDelimiter(int delim) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].delim == delim) {ret_funcs.remove(i); i--;}}
//! \brief Remove all frequency delimiters with slot \b slot.
void removeDelimiter(TimerEvent slot) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot) {ret_funcs.remove(i); i--;}}
//! \brief Remove all frequency delimiters \b delim with slot \b slot.
void removeDelimiter(int delim, TimerEvent slot) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot && ret_funcs[i].delim == delim) {ret_funcs.remove(i); i--;}}
void setDelimiterValue(int delim, int value) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].delim == delim) ret_funcs[i].tick = value;}
void setDelimiterValue(TimerEvent slot, int value) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot) ret_funcs[i].tick = value;}
void setDelimiterValue(int delim, TimerEvent slot, int value) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot && ret_funcs[i].delim == delim) ret_funcs[i].tick = value;}
int delimiterValue(int delim) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].delim == delim) return ret_funcs[i].tick; return -1;}
int delimiterValue(int delim, TimerEvent slot) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot && ret_funcs[i].delim == delim) return ret_funcs[i].tick; return -1;}
EVENT_HANDLER0(void, clearDelimiters) {ret_funcs.clear();}
//! \brief Returns nanoseconds elapsed from last \a reset() execution or from timer creation.
double elapsed_n(); // nanoseconds
//! \brief Returns microseconds elapsed from last \a reset() execution or from timer creation.
double elapsed_u(); // microseconds
//! \brief Returns milliseconds elapsed from last \a reset() execution or from timer creation.
double elapsed_m(); // milliseconds
//! \brief Returns seconds elapsed from last \a reset() execution or from timer creation.
double elapsed_s(); // seconds
double reset_time_n(); // nanoseconds
double reset_time_u(); // microseconds
double reset_time_m(); // milliseconds
double reset_time_s(); // seconds
//! \brief Returns time mark of last \a reset() execution or timer creation.
PISystemTime reset_time();
//! \brief Returns nanoseconds representation of current system time.
static double elapsed_system_n(); // nanoseconds
//! \brief Returns microseconds representation of current system time.
static double elapsed_system_u(); // microseconds
//! \brief Returns milliseconds representation of current system time.
static double elapsed_system_m(); // milliseconds
//! \brief Returns seconds representation of current system time.
static double elapsed_system_s(); // seconds
#ifdef PIP_TIMER_RT
class TimerPool: public PIThread {
public:
TimerPool(): PIThread() {/*cout << "+++++new pool\n"; */ti = -1;}
~TimerPool() {stop();}
void add(PITimer * t) {mutex.lock(); timers << TimerPair(t, 0); mutex.unlock();}
void remove(PITimer * t);
bool isEmpty() const {return timers.isEmpty();}
typedef PIPair<PITimer * , int> TimerPair;
private:
static void empty_handler(int) {}
void begin();
void run();
void end() {/*cout << "pool end\n"; */if (ti != -1) timer_delete(timer); ti = -1;}
int ti, si;
sigset_t ss;
sigevent se;
sigval sv;
itimerspec spec;
timer_t timer;
PIVector<TimerPair> timers;
PIMutex mutex;
};
static void timer_event(sigval e);
int ticks;
#endif
EVENT2(timeout, void * , data, int, delimiter)
//! \handlers
//! \{
/** \fn void reset()
* \brief Set internal time mark to current system time
* \details This function used for set start time mark. Later
* you can find out elapsed time from this time mark to any
* moment of time with \a elapsed_s(), \a elapsed_m(),
* \a elapsed_u() or \a elapsed_n() function.
* \sa \a elapsed_s(), \a elapsed_m(), \a elapsed_u(), \a elapsed_n() */
/** \fn void start(int msecs)
* \brief Start timer with \b msecs loop delay
* \details Start execution of timer functions with frequency = 1 / msecs Hz. */
/** \fn void start(double msecs)
* \brief Start timer with \b msecs loop delay
* \details Start execution of timer functions with frequency = 1. / msecs Hz.
* Instead of \a start(int msecs) function this variant allow start timer
* with frequencies more than 1 kHz. */
//! \fn void stop()
//! \brief Stop timer
/** \fn void deferredStart(double interval_msecs, double delay_msecs)
* \brief Start timer with \b interval_msecs loop delay after \b delay_msecs delay.
* \details Timer wait \b delay_msecs milliseconds and then normally starts with
* \b interval_msecs loop delay.
* \sa \a void start(double msecs), \a void deferredStart(double interval_msecs, const PIDateTime & start_datetime) */
/** \fn void deferredStart(double interval_msecs, const PIDateTime & start_datetime)
* \brief Start timer with \b interval_msecs loop delay after \b start_datetime date and time.
* \details Timer wait until \b start_datetime and then normally starts with
* \b interval_msecs loop delay.
* \sa \a void start(double msecs), \a void deferredStart(double interval_msecs, double delay_msecs) */
//! \fn void clearDelimiters()
//! \brief Remove all frequency delimiters.
//! \}
//! \events
//! \{
/** \fn void timeout(void * data, int delimiter)
* \brief Raise on timer tick
* \details \b Data can be set with function \a setData(void * data) or from constructor.
* \b Delimiter if frequency delimiter, 1 for main loop. */
//! \}
protected:
//! Virtual timer execution function, similar to "slot" or event \a void timeout(void * data, int delimiter).
//! By default is empty.
virtual void tick(void * data, int delimiter) {;}
private:
#ifndef PIP_TIMER_RT
void run();
void end() {interval_ = 0.;}
PISystemTime st_time, inc_time;
bool deferred_;
#else
bool threaded;
volatile bool lockRun;
PIMutex mutex_;
int ti;
itimerspec spec;
timer_t timer;
sigevent se;
#endif
bool running_;
double interval_;
#ifdef WINDOWS
llong pc_st, pc_cur, tt_st, tt_cur;
long
#elif defined(MAC_OS)
mach_timespec_t
#else
timespec
#endif
t_st, t_cur;
struct TimerSlot {
TimerSlot(TimerEvent slot_ = 0, int delim_ = 1) {slot = slot_; delim = delim_; tick = 0;}
TimerEvent slot;
int delim;
int tick;
};
void * data;
TimerEvent ret_func;
PIVector<TimerSlot> ret_funcs;
};
#ifdef PIP_TIMER_RT
extern PITimer::TimerPool * pool;
#endif
PIP_EXPORT PITime currentTime();
PIP_EXPORT PIDate currentDate();
PIP_EXPORT PIDateTime currentDateTime();
//! \relatesalso PISystemTime \brief Returns current system time
PIP_EXPORT PISystemTime currentSystemTime();
PIP_EXPORT PIString time2string(const PITime & time, const PIString & format = "h:mm:ss"); // obsolete, use PITime.toString() instead
PIP_EXPORT PIString date2string(const PIDate & date, const PIString & format = "d.MM.yyyy"); // obsolete, use PITime.toString() instead
PIP_EXPORT PIString datetime2string(const PIDateTime & datetime, const PIString & format = "h:mm:ss d.MM.yyyy"); // obsolete, use PIDateTime.toString() instead
#endif // PITIMER_H