2 * Copyright (C) 2005-2010 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file time.c Helper functions for dealing with time values. */
15 #include "gcc-compat.h"
22 * Convert struct timeval to milliseconds.
24 * \param tv The time value value to convert.
26 * \return The number off milliseconds in \a tv.
28 long unsigned tv2ms(const struct timeval *tv)
30 return tv->tv_sec * 1000 + (tv->tv_usec + 500)/ 1000;
34 * Convert milliseconds to a struct timeval.
36 * \param n The number of milliseconds.
37 * \param tv Result pointer.
39 void ms2tv(long unsigned n, struct timeval *tv)
41 tv->tv_sec = n / 1000;
42 tv->tv_usec = (n % 1000) * 1000;
46 * Convert a double to a struct timeval.
48 * \param x The value to convert.
49 * \param tv Result pointer.
51 void d2tv(double x, struct timeval *tv)
54 tv->tv_usec = (x - (double)tv->tv_sec) * 1000.0 * 1000.0 + 0.5;
58 * Compute the difference of two time values.
61 * \param a Subtrahend.
62 * \param diff Result pointer.
64 * If \a diff is not \p NULL, it contains the absolute value |\a b - \a a| on
67 * \return If \a b < \a a, this function returns -1, otherwise it returns 1.
69 int tv_diff(const struct timeval *b, const struct timeval *a, struct timeval *diff)
73 if ((b->tv_sec < a->tv_sec) ||
74 ((b->tv_sec == a->tv_sec) && (b->tv_usec < a->tv_usec))) {
75 const struct timeval *tmp = a;
82 diff->tv_sec = b->tv_sec - a->tv_sec;
83 if (b->tv_usec < a->tv_usec) {
85 diff->tv_usec = 1000 * 1000 - a->tv_usec + b->tv_usec;
87 diff->tv_usec = b->tv_usec - a->tv_usec;
92 * Add two time values.
94 * \param a First addend.
95 * \param b Second addend.
96 * \param sum Contains the sum \a + \a b on return.
98 void tv_add(const struct timeval *a, const struct timeval *b,
101 sum->tv_sec = a->tv_sec + b->tv_sec;
102 if (a->tv_usec + b->tv_usec >= 1000 * 1000) {
104 sum->tv_usec = a->tv_usec + b->tv_usec - 1000 * 1000;
106 sum->tv_usec = a->tv_usec + b->tv_usec;
110 * Compute integer multiple of given struct timeval.
112 * \param mult The integer value to multiply with.
113 * \param tv The timevalue to multiply.
115 * \param result Contains \a mult * \a tv on return.
117 void tv_scale(const unsigned long mult, const struct timeval *tv,
118 struct timeval *result)
120 result->tv_sec = mult * tv->tv_sec;
121 result->tv_sec += tv->tv_usec * mult / 1000 / 1000;
122 result->tv_usec = tv->tv_usec * mult % (1000 * 1000);
126 * Compute a fraction of given struct timeval.
128 * \param divisor The integer value to divide by.
129 * \param tv The timevalue to divide.
130 * \param result Contains (1 / mult) * tv on return.
132 void tv_divide(const unsigned long divisor, const struct timeval *tv,
133 struct timeval *result)
135 uint64_t x = ((uint64_t)tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
137 result->tv_sec = x / 1000 / 1000;
138 result->tv_usec = x % (1000 * 1000);
141 int64_t get_current_time(void)
145 DSS_DEBUG_LOG("now: %jd\n", (intmax_t)now);