blob: c2a2617e8571c54756c2f5543c59a8ebd016c17e [file] [log] [blame]
dburgess82c46ff2011-10-07 02:40:51 +00001/*
2* Copyright 2008 Free Software Foundation, Inc.
3*
4* This software is distributed under the terms of the GNU Affero Public License.
5* See the COPYING file in the main directory for details.
6*
7* This use of this software may be subject to additional restrictions.
8* See the LEGAL file in the main directory for details.
9
10 This program is free software: you can redistribute it and/or modify
11 it under the terms of the GNU Affero General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU Affero General Public License for more details.
19
20 You should have received a copy of the GNU Affero General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
22
23*/
24
25
26#ifndef TIMEVAL_H
27#define TIMEVAL_H
28
29#include <stdint.h>
30#include "sys/time.h"
31#include <iostream>
32
33
34
35/** A wrapper on usleep to sleep for milliseconds. */
36inline void msleep(long v) { usleep(v*1000); }
37
38
39/** A C++ wrapper for struct timeval. */
40class Timeval {
41
42 private:
43
44 struct timeval mTimeval;
45
46 public:
47
48 /** Set the value to gettimeofday. */
49 void now() { gettimeofday(&mTimeval,NULL); }
50
51 /** Set the value to gettimeofday plus an offset. */
52 void future(unsigned ms);
53
54 //@{
55 Timeval(unsigned sec, unsigned usec)
56 {
57 mTimeval.tv_sec = sec;
58 mTimeval.tv_usec = usec;
59 }
60
61 Timeval(const struct timeval& wTimeval)
62 :mTimeval(wTimeval)
63 {}
64
65 /**
66 Create a Timeval offset into the future.
67 @param offset milliseconds
68 */
69 Timeval(unsigned offset=0) { future(offset); }
70 //@}
71
72 /** Convert to a struct timespec. */
73 struct timespec timespec() const;
74
75 /** Return total seconds. */
76 double seconds() const;
77
78 uint32_t sec() const { return mTimeval.tv_sec; }
79 uint32_t usec() const { return mTimeval.tv_usec; }
80
81 /** Return differnce from other (other-self), in ms. */
82 long delta(const Timeval& other) const;
83
84 /** Elapsed time in ms. */
85 long elapsed() const { return delta(Timeval()); }
86
87 /** Remaining time in ms. */
88 long remaining() const { return -elapsed(); }
89
90 /** Return true if the time has passed, as per gettimeofday. */
91 bool passed() const;
92
93 /** Add a given number of minutes to the time. */
94 void addMinutes(unsigned minutes) { mTimeval.tv_sec += minutes*60; }
95
96};
97
98std::ostream& operator<<(std::ostream& os, const Timeval&);
99
100std::ostream& operator<<(std::ostream& os, const struct timespec&);
101
102
103#endif
104// vim: ts=4 sw=4