aboutsummaryrefslogtreecommitdiff
path: root/src/timing.c
blob: 1a06f53b0a8e2df3fc950487f6a08b9a1532ec0c (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
/****************************************************************************
 * Timing functions.
 * Copyright (C) 2004 Joe Wingbermuehle
 ****************************************************************************/

#include "jwm.h"
#include "timing.h"

static const unsigned long MAX_TIME_SECONDS = 60;

/****************************************************************************
 * Get the current time in milliseconds since midnight 1970-01-01 UTC.
 ****************************************************************************/
void
GetCurrentTime(TimeType *t)
{
	struct timeval val;
	gettimeofday(&val, NULL);
	t->seconds = val.tv_sec;
	t->ms = val.tv_usec / 1000;
}

/****************************************************************************
 * Get the absolute difference between two times in milliseconds.
 * If the difference is larger than a MAX_TIME_SECONDS, then
 * MAX_TIME_SECONDS will be returned.
 * Note that the times must be normalized.
 ****************************************************************************/
unsigned long
GetTimeDifference(const TimeType *t1, const TimeType *t2)
{
	unsigned long deltaSeconds;
	int deltaMs;

	if(t1->seconds > t2->seconds) {
		deltaSeconds = t1->seconds - t2->seconds;
		deltaMs = t1->ms - t2->ms;
	} else if(t1->seconds < t2->seconds) {
		deltaSeconds = t2->seconds - t1->seconds;
		deltaMs = t2->ms - t1->ms;
	} else if(t1->ms > t2->ms) {
		deltaSeconds = 0;
		deltaMs = t1->ms - t2->ms;
	} else {
		deltaSeconds = 0;
		deltaMs = t2->ms - t1->ms;
	}

	if(deltaSeconds > MAX_TIME_SECONDS) {
		return MAX_TIME_SECONDS * 1000;
	} else {
		return deltaSeconds * 1000 + deltaMs;
	}

}

/****************************************************************************
 * Get the current time.
 * Not reenterent.
 ****************************************************************************/
const char *
GetTimeString(const char *format)
{

	static char str[80];
	time_t t;

	Assert(format);

	time(&t);
	strftime(str, sizeof(str), format, localtime(&t));

	return str;

}