summaryrefslogtreecommitdiff
path: root/test/lib/time.c
blob: b99e738c500fb159c2065fbdb8349a991971faf7 (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
97
98
99
100
101
102
103
104
105
106
// SPDX-License-Identifier: GPL-2.0+
/*
 * Copyright (c) 2015 Google, Inc
 * Written by Simon Glass <sjg@chromium.org>
 */

#include <errno.h>
#include <time.h>
#include <linux/delay.h>
#include <test/lib.h>
#include <test/ut.h>

static int test_get_timer(struct unit_test_state *uts)
{
	ulong base, start, next, diff;
	int iter;

	base = get_timer(0);
	start = get_timer(0);
	for (iter = 0; iter < 10; iter++) {
		do {
			next = get_timer(0);
		} while (start == next);

		ut_asserteq(start + 1, next);
		start++;
	}

	/*
	 * Check that get_timer(base) matches our elapsed time, allowing that
	 * an extra millisecond may have passed.
	 */
	diff = get_timer(base);
	ut_assert(diff == iter || diff == iter + 1);

	return 0;
}
LIB_TEST(test_get_timer, 0);

static int test_timer_get_us(struct unit_test_state *uts)
{
	ulong prev, next, min = 1000000;
	long delta;
	int iter;

	/* Find the minimum delta we can measure, in microseconds */
	prev = timer_get_us();
	for (iter = 0; iter < 100; ) {
		next = timer_get_us();
		if (next != prev) {
			delta = next - prev;
			ut_assert(delta >= 0);
			if (delta) {
				if (delta < min)
					min = delta;
				prev = next;
				iter++;
			}
		}
	}

	ut_asserteq(1, min);

	return 0;
}
LIB_TEST(test_timer_get_us, 0);

static int test_time_comparison(struct unit_test_state *uts)
{
	ulong start_us, end_us, delta_us;
	long error;
	ulong start;

	start = get_timer(0);
	start_us = timer_get_us();
	while (get_timer(start) < 1000)
		;
	end_us = timer_get_us();
	delta_us = end_us - start_us;
	error = delta_us - 1000000;
	printf("%s: Microsecond time for 1 second: %lu, error = %ld\n",
	       __func__, delta_us, error);
	ut_assert(abs(error) <= 1000);

	return 0;
}
LIB_TEST(test_time_comparison, 0);

static int test_udelay(struct unit_test_state *uts)
{
	long error;
	ulong start, delta;
	int iter;

	start = get_timer(0);
	for (iter = 0; iter < 1000; iter++)
		udelay(1000);
	delta = get_timer(start);
	error = delta - 1000;
	printf("%s: Delay time for 1000 udelay(1000): %lu ms, error = %ld\n",
	       __func__, delta, error);
	ut_assert(abs(error) <= 100);

	return 0;
}
LIB_TEST(test_udelay, 0);