3 // $Id: time.cpp,v 1.4 2008/07/15 20:33:31 hartwork Exp $
5 // CppTest - A C++ Unit Testing Framework
6 // Copyright (c) 2003 Niklas Lundell
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2 of the License, or (at your option) any later version.
15 // This library 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 GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the
22 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 // Boston, MA 02111-1307, USA.
27 #if (defined(__WIN32__) || defined(WIN32))
28 # include "winconfig.h"
34 #include "cpptest-time.h"
36 #ifdef HAVE_GETTIMEOFDAY
37 #ifdef HAVE_SYS_TIME_H
50 const unsigned int UsecPerSec
= 1000000;
52 } // anonymous namespace
54 /// Constructs a time object with zeroed time.
61 /// Constructs a time object.
63 /// \param sec Seconds.
64 /// \param usec Micro-seconds.
66 Time::Time(unsigned int sec
, unsigned int usec
)
79 /// \return Micro-seconds.
82 Time::microseconds() const
87 /// \return The current time.
94 return Time(tv
.tv_sec
, tv
.tv_usec
);
99 /// Computes the time elapsed between two time values.
101 /// \param t1 Left-hand time, should be greater than \a t2.
102 /// \param t2 Right-hand time, should be less than \a t1.
104 /// \return Computed time value.
107 operator-(const Time
& t1
, const Time
& t2
)
109 if (t2
._sec
> t1
._sec
|| (t2
._sec
== t1
._sec
&& t2
._usec
> t1
._usec
))
112 unsigned int sec
= t1
._sec
- t2
._sec
;
115 if (t2
._usec
> t1
._usec
)
118 usec
= UsecPerSec
- (t2
._usec
- t1
._usec
);
121 usec
= t1
._usec
- t2
._usec
;
123 return Time(sec
, usec
);
128 /// Adds two time values.
130 /// \param t1 Left-hand time.
131 /// \param t2 Right-hand time.
133 /// \return Computed time value.
136 operator+(const Time
& t1
, const Time
& t2
)
138 unsigned int sec
= t1
._sec
+ t2
._sec
;
139 unsigned int usec
= t1
._usec
+ t2
._usec
;
141 if (usec
> UsecPerSec
)
146 return Time(sec
, usec
);
151 /// Outputs a time to an output stream.
153 /// \param os Output stream to write to.
154 /// \param t %Time to output.
156 /// \return A reference to the given output stream.
159 operator<<(ostream
& os
, const Time
& t
)
161 int old_fill(os
.fill());
162 int old_width(os
.width());
164 os
<< t
.seconds() << '.';
167 os
<< t
.microseconds();