summaryrefslogtreecommitdiff
path: root/tv.c
blob: 6214ff63da55ab0c2fe7c43b2bcc5f34a502b66b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* SPDX-License-Identifier: GPL-2.0 */

#include <sys/time.h>
#include <time.h>
#include <inttypes.h>
#include <assert.h>
#include <string.h>

#include "gcc-compat.h"
#include "err.h"
#include "str.h"
#include "log.h"
#include "time.h"

/*
 * Compute the difference of two time values.  If b < a the function returns
 * -1, otherwise it returns 1. If diff is not NULL, |b - a| is returned through
 * this pointer.
 */
int tv_diff(const struct timeval *b, const struct timeval *a, struct timeval *diff)
{
	int ret = 1;

	if ((b->tv_sec < a->tv_sec) ||
		((b->tv_sec == a->tv_sec) && (b->tv_usec < a->tv_usec))) {
		const struct timeval *tmp = a;
		a = b;
		b = tmp;
		ret = -1;
	}
	if (!diff)
		return ret;
	diff->tv_sec = b->tv_sec - a->tv_sec;
	if (b->tv_usec < a->tv_usec) {
		diff->tv_sec--;
		diff->tv_usec = 1000 * 1000 - a->tv_usec + b->tv_usec;
	} else
		diff->tv_usec = b->tv_usec - a->tv_usec;
	return ret;
}

int64_t get_current_time(void)
{
	time_t now;
	time(&now);
	return (int64_t)now;
}