summaryrefslogtreecommitdiff
path: root/src/gtm/common/gtm_time.c
blob: d121822743ab51b73d0239e57a5f6abe33d673f3 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*-------------------------------------------------------------------------
 *
 * gtm_time.c
 *			Timestamp handling on GTM
 *
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 * Portions Copyright (c) 2010-2012 Postgres-XC Development Group
 *
 *
 * IDENTIFICATION
 *			$PostgreSQL$
 *
 *-------------------------------------------------------------------------
 */

#include "gtm/gtm.h"
#include "gtm/gtm_c.h"
#include "gtm/gtm_time.h"
#include <time.h>
#include <sys/time.h>

GTM_Timestamp
GTM_TimestampGetCurrent(void)
{
	struct timeval	tp;
	GTM_Timestamp	result;

	gettimeofday(&tp, NULL);

	result = (GTM_Timestamp) tp.tv_sec -
	((GTM_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);

#ifdef HAVE_INT64_TIMESTAMP
	result = (result * USECS_PER_SEC) + tp.tv_usec;
#else
	result = result + (tp.tv_usec / 1000000.0);
#endif

	return result;
}

/*
 * TimestampDifference -- convert the difference between two timestamps
 *		into integer seconds and microseconds
 *
 * Both inputs must be ordinary finite timestamps (in current usage,
 * they'll be results from GTM_TimestampGetCurrent()).
 *
 * We expect start_time <= stop_time.  If not, we return zeroes; for current
 * callers there is no need to be tense about which way division rounds on
 * negative inputs.
 */
void
GTM_TimestampDifference(GTM_Timestamp start_time, GTM_Timestamp stop_time,
					long *secs, int *microsecs)
{
	GTM_Timestamp diff = stop_time - start_time;

	if (diff <= 0)
	{
		*secs = 0;
		*microsecs = 0;
	}
	else
	{
#ifdef HAVE_INT64_TIMESTAMP
		*secs = (long) (diff / USECS_PER_SEC);
		*microsecs = (int) (diff % USECS_PER_SEC);
#else
		*secs = (long) diff;
		*microsecs = (int) ((diff - *secs) * 1000000.0);
#endif
	}
}

/*
 * GTM_TimestampDifferenceExceeds -- report whether the difference between two
 *		timestamps is >= a threshold (expressed in milliseconds)
 *
 * Both inputs must be ordinary finite timestamps (in current usage,
 * they'll be results from GTM_TimestampDifferenceExceeds()).
 */
bool
GTM_TimestampDifferenceExceeds(GTM_Timestamp start_time,
						   GTM_Timestamp stop_time,
						   int msec)
{
	GTM_Timestamp diff = stop_time - start_time;

#ifdef HAVE_INT64_TIMESTAMP
	return (diff >= msec * INT64CONST(1000));
#else
	return (diff * 1000.0 >= msec);
#endif
}