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"
20 * Convert struct timeval to milliseconds.
22 * \param tv The time value value to convert.
24 * \return The number off milliseconds in \a tv.
26 long unsigned tv2ms(const struct timeval *tv)
28 return tv->tv_sec * 1000 + (tv->tv_usec + 500)/ 1000;
32 * Convert milliseconds to a struct timeval.
34 * \param n The number of milliseconds.
35 * \param tv Result pointer.
37 void ms2tv(long unsigned n, struct timeval *tv)
39 tv->tv_sec = n / 1000;
40 tv->tv_usec = (n % 1000) * 1000;
44 * Convert a double to a struct timeval.
46 * \param x The value to convert.
47 * \param tv Result pointer.
49 void d2tv(double x, struct timeval *tv)
52 tv->tv_usec = (x - (double)tv->tv_sec) * 1000.0 * 1000.0 + 0.5;
56 * Compute the difference of two time values.
59 * \param a Subtrahend.
60 * \param diff Result pointer.
62 * If \a diff is not \p NULL, it contains the absolute value |\a b - \a a| on
65 * \return If \a b < \a a, this function returns -1, otherwise it returns 1.
67 int tv_diff(const struct timeval *b, const struct timeval *a, struct timeval *diff)
71 if ((b->tv_sec < a->tv_sec) ||
72 ((b->tv_sec == a->tv_sec) && (b->tv_usec < a->tv_usec))) {
73 const struct timeval *tmp = a;
80 diff->tv_sec = b->tv_sec - a->tv_sec;
81 if (b->tv_usec < a->tv_usec) {
83 diff->tv_usec = 1000 * 1000 - a->tv_usec + b->tv_usec;
85 diff->tv_usec = b->tv_usec - a->tv_usec;
90 * Add two time values.
92 * \param a First addend.
93 * \param b Second addend.
94 * \param sum Contains the sum \a + \a b on return.
96 void tv_add(const struct timeval *a, const struct timeval *b,
99 sum->tv_sec = a->tv_sec + b->tv_sec;
100 if (a->tv_usec + b->tv_usec >= 1000 * 1000) {
102 sum->tv_usec = a->tv_usec + b->tv_usec - 1000 * 1000;
104 sum->tv_usec = a->tv_usec + b->tv_usec;
108 * Compute integer multiple of given struct timeval.
110 * \param mult The integer value to multiply with.
111 * \param tv The timevalue to multiply.
113 * \param result Contains \a mult * \a tv on return.
115 void tv_scale(const unsigned long mult, const struct timeval *tv,
116 struct timeval *result)
118 result->tv_sec = mult * tv->tv_sec;
119 result->tv_sec += tv->tv_usec * mult / 1000 / 1000;
120 result->tv_usec = tv->tv_usec * mult % (1000 * 1000);
124 * Compute a fraction of given struct timeval.
126 * \param divisor The integer value to divide by.
127 * \param tv The timevalue to divide.
128 * \param result Contains (1 / mult) * tv on return.
130 void tv_divide(const unsigned long divisor, const struct timeval *tv,
131 struct timeval *result)
133 uint64_t x = ((uint64_t)tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
135 result->tv_sec = x / 1000 / 1000;
136 result->tv_usec = x % (1000 * 1000);
139 int64_t get_current_time(void)
143 DSS_DEBUG_LOG(("now: %jd\n", (intmax_t)now));