1 // SPDX-License-Identifier: GPL-2.0-or-later
3 /***************************************************************************
4 * Copyright (C) 2006 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
7 * Copyright (C) 2007,2008 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
10 * Copyright (C) 2008 by Spencer Oliver *
11 * spen@spen-soft.co.uk *
12 ***************************************************************************/
18 #include "time_support.h"
20 /* calculate difference between two struct timeval values */
21 int timeval_subtract(struct timeval
*result
, struct timeval
*x
, struct timeval
*y
)
23 if (x
->tv_usec
< y
->tv_usec
) {
24 int nsec
= (y
->tv_usec
- x
->tv_usec
) / 1000000 + 1;
25 y
->tv_usec
-= 1000000 * nsec
;
28 if (x
->tv_usec
- y
->tv_usec
> 1000000) {
29 int nsec
= (x
->tv_usec
- y
->tv_usec
) / 1000000;
30 y
->tv_usec
+= 1000000 * nsec
;
34 result
->tv_sec
= x
->tv_sec
- y
->tv_sec
;
35 result
->tv_usec
= x
->tv_usec
- y
->tv_usec
;
37 /* Return 1 if result is negative. */
38 return x
->tv_sec
< y
->tv_sec
;
41 int timeval_add_time(struct timeval
*result
, long sec
, long usec
)
43 result
->tv_sec
+= sec
;
44 result
->tv_usec
+= usec
;
46 while (result
->tv_usec
> 1000000) {
47 result
->tv_usec
-= 1000000;
54 /* compare two timevals and return -1/0/+1 accordingly */
55 int timeval_compare(const struct timeval
*x
, const struct timeval
*y
)
57 if (x
->tv_sec
< y
->tv_sec
)
59 else if (x
->tv_sec
> y
->tv_sec
)
61 else if (x
->tv_usec
< y
->tv_usec
)
63 else if (x
->tv_usec
> y
->tv_usec
)
69 int duration_start(struct duration
*duration
)
71 return gettimeofday(&duration
->start
, NULL
);
74 int duration_measure(struct duration
*duration
)
77 int retval
= gettimeofday(&end
, NULL
);
79 timeval_subtract(&duration
->elapsed
, &end
, &duration
->start
);
83 float duration_elapsed(const struct duration
*duration
)
85 float t
= duration
->elapsed
.tv_sec
;
86 t
+= (float)duration
->elapsed
.tv_usec
/ 1000000.0;
90 float duration_kbps(const struct duration
*duration
, size_t count
)
92 return count
/ (1024.0 * duration_elapsed(duration
));