summaryrefslogtreecommitdiff
path: root/test/src/timer.c
blob: 0f39d5f6000836a5fa828665f1bc42bc7ccf6d4f (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
#include "test/jemalloc_test.h"

void
timer_start(timedelta_t *timer) {
	nstime_init_update(&timer->t0);
}

void
timer_stop(timedelta_t *timer) {
	nstime_copy(&timer->t1, &timer->t0);
	nstime_update(&timer->t1);
}

uint64_t
timer_usec(const timedelta_t *timer) {
	nstime_t delta;

	nstime_copy(&delta, &timer->t1);
	nstime_subtract(&delta, &timer->t0);
	return nstime_ns(&delta) / 1000;
}

void
timer_ratio(timedelta_t *a, timedelta_t *b, char *buf, size_t buflen) {
	uint64_t t0 = timer_usec(a);
	uint64_t t1 = timer_usec(b);
	uint64_t mult;
	size_t i = 0;
	size_t j, n;

	/* 
 	* The time difference could be 0 if the two clock readings are 
 	* identical, either due to the operations being measured in the middle
 	* took very little time (or even got optimized away), or the clock 
 	* readings are bad / very coarse grained clock.
 	* Thus, bump t1 if it is 0 to avoid dividing 0. 
 	*/
	if (t1 == 0) {
	    t1 = 1;
	}

	/* Whole. */
	n = malloc_snprintf(&buf[i], buflen-i, "%"FMTu64, t0 / t1);
	i += n;
	if (i >= buflen) {
		return;
	}
	mult = 1;
	for (j = 0; j < n; j++) {
		mult *= 10;
	}

	/* Decimal. */
	n = malloc_snprintf(&buf[i], buflen-i, ".");
	i += n;

	/* Fraction. */
	while (i < buflen-1) {
		uint64_t round = (i+1 == buflen-1 && ((t0 * mult * 10 / t1) % 10
		    >= 5)) ? 1 : 0;
		n = malloc_snprintf(&buf[i], buflen-i,
		    "%"FMTu64, (t0 * mult / t1) % 10 + round);
		i += n;
		mult *= 10;
	}
}