6 * Copyright (C) 2005-2008 Andre Noll <maan@systemlinux.org>
8 * Licensed under the GPL v2. For licencing details see COPYING.
11 /** \file time.c Helper functions for dealing with time values. */
14 * Convert struct timeval to milliseconds.
16 * \param tv The time value value to convert.
18 * \return The number off milliseconds in \a tv.
20 long unsigned tv2ms(const struct timeval
*tv
)
22 return tv
->tv_sec
* 1000 + (tv
->tv_usec
+ 500)/ 1000;
26 * Convert milliseconds to a struct timeval.
28 * \param n The number of milliseconds.
29 * \param tv Result pointer.
31 void ms2tv(long unsigned n
, struct timeval
*tv
)
33 tv
->tv_sec
= n
/ 1000;
34 tv
->tv_usec
= (n
% 1000) * 1000;
38 * Convert a double to a struct timeval.
40 * \param x The value to convert.
41 * \param tv Result pointer.
43 void d2tv(double x
, struct timeval
*tv
)
46 tv
->tv_usec
= (x
- (double)tv
->tv_sec
) * 1000.0 * 1000.0 + 0.5;
50 * Compute the difference of two time values.
53 * \param a Subtrahend.
54 * \param diff Result pointer.
56 * If \a diff is not \p NULL, it contains the absolute value |\a b - \a a| on
59 * \return If \a b < \a a, this function returns -1, otherwise it returns 1.
61 int tv_diff(const struct timeval
*b
, const struct timeval
*a
, struct timeval
*diff
)
65 if ((b
->tv_sec
< a
->tv_sec
) ||
66 ((b
->tv_sec
== a
->tv_sec
) && (b
->tv_usec
< a
->tv_usec
))) {
67 const struct timeval
*tmp
= a
;
74 diff
->tv_sec
= b
->tv_sec
- a
->tv_sec
;
75 if (b
->tv_usec
< a
->tv_usec
) {
77 diff
->tv_usec
= 1000 * 1000 - a
->tv_usec
+ b
->tv_usec
;
79 diff
->tv_usec
= b
->tv_usec
- a
->tv_usec
;
84 * Add two time values.
86 * \param a First addend.
87 * \param b Second addend.
88 * \param sum Contains the sum \a + \a b on return.
90 void tv_add(const struct timeval
*a
, const struct timeval
*b
,
93 sum
->tv_sec
= a
->tv_sec
+ b
->tv_sec
;
94 if (a
->tv_usec
+ b
->tv_usec
>= 1000 * 1000) {
96 sum
->tv_usec
= a
->tv_usec
+ b
->tv_usec
- 1000 * 1000;
98 sum
->tv_usec
= a
->tv_usec
+ b
->tv_usec
;
102 * Compute integer multiple of given struct timeval.
104 * \param mult The integer value to multiply with.
105 * \param tv The timevalue to multiply.
107 * \param result Contains \a mult * \a tv on return.
109 void tv_scale(const unsigned long mult
, const struct timeval
*tv
,
110 struct timeval
*result
)
112 result
->tv_sec
= mult
* tv
->tv_sec
;
113 result
->tv_sec
+= tv
->tv_usec
* mult
/ 1000 / 1000;
114 result
->tv_usec
= tv
->tv_usec
* mult
% (1000 * 1000);
118 * Compute a fraction of given struct timeval.
120 * \param divisor The integer value to divide by.
121 * \param tv The timevalue to divide.
122 * \param result Contains (1 / mult) * tv on return.
124 void tv_divide(const unsigned long divisor
, const struct timeval
*tv
,
125 struct timeval
*result
)
127 uint64_t x
= ((uint64_t)tv
->tv_sec
* 1000 * 1000 + tv
->tv_usec
) / divisor
;
129 result
->tv_sec
= x
/ 1000 / 1000;
130 result
->tv_usec
= x
% (1000 * 1000);