2 * Copyright (C) 2005-2009 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"
21 * Convert struct timeval to milliseconds.
23 * \param tv The time value value to convert.
25 * \return The number off milliseconds in \a tv.
27 long unsigned tv2ms(const struct timeval *tv)
29 return tv->tv_sec * 1000 + (tv->tv_usec + 500)/ 1000;
33 * Convert milliseconds to a struct timeval.
35 * \param n The number of milliseconds.
36 * \param tv Result pointer.
38 void ms2tv(long unsigned n, struct timeval *tv)
40 tv->tv_sec = n / 1000;
41 tv->tv_usec = (n % 1000) * 1000;
45 * Convert a double to a struct timeval.
47 * \param x The value to convert.
48 * \param tv Result pointer.
50 void d2tv(double x, struct timeval *tv)
53 tv->tv_usec = (x - (double)tv->tv_sec) * 1000.0 * 1000.0 + 0.5;
57 * Compute the difference of two time values.
60 * \param a Subtrahend.
61 * \param diff Result pointer.
63 * If \a diff is not \p NULL, it contains the absolute value |\a b - \a a| on
66 * \return If \a b < \a a, this function returns -1, otherwise it returns 1.
68 int tv_diff(const struct timeval *b, const struct timeval *a, struct timeval *diff)
72 if ((b->tv_sec < a->tv_sec) ||
73 ((b->tv_sec == a->tv_sec) && (b->tv_usec < a->tv_usec))) {
74 const struct timeval *tmp = a;
81 diff->tv_sec = b->tv_sec - a->tv_sec;
82 if (b->tv_usec < a->tv_usec) {
84 diff->tv_usec = 1000 * 1000 - a->tv_usec + b->tv_usec;
86 diff->tv_usec = b->tv_usec - a->tv_usec;
91 * Add two time values.
93 * \param a First addend.
94 * \param b Second addend.
95 * \param sum Contains the sum \a + \a b on return.
97 void tv_add(const struct timeval *a, const struct timeval *b,
100 sum->tv_sec = a->tv_sec + b->tv_sec;
101 if (a->tv_usec + b->tv_usec >= 1000 * 1000) {
103 sum->tv_usec = a->tv_usec + b->tv_usec - 1000 * 1000;
105 sum->tv_usec = a->tv_usec + b->tv_usec;
109 * Compute integer multiple of given struct timeval.
111 * \param mult The integer value to multiply with.
112 * \param tv The timevalue to multiply.
114 * \param result Contains \a mult * \a tv on return.
116 void tv_scale(const unsigned long mult, const struct timeval *tv,
117 struct timeval *result)
119 result->tv_sec = mult * tv->tv_sec;
120 result->tv_sec += tv->tv_usec * mult / 1000 / 1000;
121 result->tv_usec = tv->tv_usec * mult % (1000 * 1000);
125 * Compute a fraction of given struct timeval.
127 * \param divisor The integer value to divide by.
128 * \param tv The timevalue to divide.
129 * \param result Contains (1 / mult) * tv on return.
131 void tv_divide(const unsigned long divisor, const struct timeval *tv,
132 struct timeval *result)
134 uint64_t x = ((uint64_t)tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
136 result->tv_sec = x / 1000 / 1000;
137 result->tv_usec = x % (1000 * 1000);
140 int64_t get_current_time(void)
144 DSS_DEBUG_LOG("now: %jd\n", (intmax_t)now);