2 * Copyright (C) 2005-2010 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
13 #include "gcc-compat.h"
19 * Convert struct timeval to milliseconds.
21 * \param tv The time value value to convert.
23 * \return The number off milliseconds in \a tv.
25 long unsigned tv2ms(const struct timeval *tv)
27 return tv->tv_sec * 1000 + (tv->tv_usec + 500)/ 1000;
31 * Convert milliseconds to a struct timeval.
33 * \param n The number of milliseconds.
34 * \param tv Result pointer.
36 void ms2tv(long unsigned n, struct timeval *tv)
38 tv->tv_sec = n / 1000;
39 tv->tv_usec = (n % 1000) * 1000;
43 * Convert a double to a struct timeval.
45 * \param x The value to convert.
46 * \param tv Result pointer.
48 void d2tv(double x, struct timeval *tv)
51 tv->tv_usec = (x - (double)tv->tv_sec) * 1000.0 * 1000.0 + 0.5;
55 * Compute the difference of two time values.
58 * \param a Subtrahend.
59 * \param diff Result pointer.
61 * If \a diff is not \p NULL, it contains the absolute value |\a b - \a a| on
64 * \return If \a b < \a a, this function returns -1, otherwise it returns 1.
66 int tv_diff(const struct timeval *b, const struct timeval *a, struct timeval *diff)
70 if ((b->tv_sec < a->tv_sec) ||
71 ((b->tv_sec == a->tv_sec) && (b->tv_usec < a->tv_usec))) {
72 const struct timeval *tmp = a;
79 diff->tv_sec = b->tv_sec - a->tv_sec;
80 if (b->tv_usec < a->tv_usec) {
82 diff->tv_usec = 1000 * 1000 - a->tv_usec + b->tv_usec;
84 diff->tv_usec = b->tv_usec - a->tv_usec;
89 * Add two time values.
91 * \param a First addend.
92 * \param b Second addend.
93 * \param sum Contains the sum \a + \a b on return.
95 void tv_add(const struct timeval *a, const struct timeval *b,
98 sum->tv_sec = a->tv_sec + b->tv_sec;
99 if (a->tv_usec + b->tv_usec >= 1000 * 1000) {
101 sum->tv_usec = a->tv_usec + b->tv_usec - 1000 * 1000;
103 sum->tv_usec = a->tv_usec + b->tv_usec;
107 * Compute integer multiple of given struct timeval.
109 * \param mult The integer value to multiply with.
110 * \param tv The timevalue to multiply.
112 * \param result Contains \a mult * \a tv on return.
114 void tv_scale(const unsigned long mult, const struct timeval *tv,
115 struct timeval *result)
117 result->tv_sec = mult * tv->tv_sec;
118 result->tv_sec += tv->tv_usec * mult / 1000 / 1000;
119 result->tv_usec = tv->tv_usec * mult % (1000 * 1000);
123 * Compute a fraction of given struct timeval.
125 * \param divisor The integer value to divide by.
126 * \param tv The timevalue to divide.
127 * \param result Contains (1 / mult) * tv on return.
129 void tv_divide(const unsigned long divisor, const struct timeval *tv,
130 struct timeval *result)
132 uint64_t x = ((uint64_t)tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
134 result->tv_sec = x / 1000 / 1000;
135 result->tv_usec = x % (1000 * 1000);
138 int64_t get_current_time(void)
142 DSS_DEBUG_LOG("now: %jd\n", (intmax_t)now);