1///////////////////////////////////////////////////////////////////////////////
2//
3/// \file       mytime.c
4/// \brief      Time handling functions
5//
6//  Author:     Lasse Collin
7//
8//  This file has been put into the public domain.
9//  You can do whatever you want with this file.
10//
11///////////////////////////////////////////////////////////////////////////////
12
13#include "private.h"
14
15#if !(defined(HAVE_CLOCK_GETTIME) && HAVE_DECL_CLOCK_MONOTONIC)
16#	include <sys/time.h>
17#endif
18
19uint64_t opt_flush_timeout = 0;
20
21static uint64_t start_time;
22static uint64_t next_flush;
23
24
25/// \brief      Get the current time as milliseconds
26///
27/// It's relative to some point but not necessarily to the UNIX Epoch.
28static uint64_t
29mytime_now(void)
30{
31	// NOTE: HAVE_DECL_CLOCK_MONOTONIC is always defined to 0 or 1.
32#if defined(HAVE_CLOCK_GETTIME) && HAVE_DECL_CLOCK_MONOTONIC
33	// If CLOCK_MONOTONIC was available at compile time but for some
34	// reason isn't at runtime, fallback to CLOCK_REALTIME which
35	// according to POSIX is mandatory for all implementations.
36	static clockid_t clk_id = CLOCK_MONOTONIC;
37	struct timespec tv;
38	while (clock_gettime(clk_id, &tv))
39		clk_id = CLOCK_REALTIME;
40
41	return (uint64_t)tv.tv_sec * 1000 + (uint64_t)(tv.tv_nsec / 1000000);
42#else
43	struct timeval tv;
44	gettimeofday(&tv, NULL);
45	return (uint64_t)tv.tv_sec * 1000 + (uint64_t)(tv.tv_usec / 1000);
46#endif
47}
48
49
50extern void
51mytime_set_start_time(void)
52{
53	start_time = mytime_now();
54	return;
55}
56
57
58extern uint64_t
59mytime_get_elapsed(void)
60{
61	return mytime_now() - start_time;
62}
63
64
65extern void
66mytime_set_flush_time(void)
67{
68	next_flush = mytime_now() + opt_flush_timeout;
69	return;
70}
71
72
73extern int
74mytime_get_flush_timeout(void)
75{
76	if (opt_flush_timeout == 0 || opt_mode != MODE_COMPRESS)
77		return -1;
78
79	const uint64_t now = mytime_now();
80	if (now >= next_flush)
81		return 0;
82
83	const uint64_t remaining = next_flush - now;
84	return remaining > INT_MAX ? INT_MAX : (int)remaining;
85}
86