aboutsummaryrefslogtreecommitdiffstats
path: root/src/time/benchmark.c
blob: 543275a0f745135c0a022bc5ef47a85d2d7931d8 (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
/*
 * The Rin Library – time module, benchmarking section
 *
 * Copyright (C) 2019 Gediminas Jakutis
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; version 2.1
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <time.h>
#include <errno.h>
#include <sys/resource.h>
#include "rin/time.h"
#include "time_private.h"

#if defined CLOCK_MONOTONIC
#	define RIN_CLOCK_WALL_COUNTER CLOCK_MONOTONIC
#else
#	define RIN_CLOCK_WALL_COUNTER CLOCK_REALTIME
#endif /* defined CLOCK_MONOTONIC */

static struct bench {
	int status;
	struct rusage runtime;
	struct timespec wall;
} bench = {0};


int rin_bench_start(void)
{
	if (bench.status) {
		return EAGAIN;
	}

	bench.status = 1;
	clock_gettime(RIN_CLOCK_WALL_COUNTER, &bench.wall);
	getrusage(RUSAGE_SELF, &bench.runtime);

	return 0;
}

int rin_bench_stop(struct rin_bench_result *res)
{
	struct timespec wall;
	struct rusage run;

	if (!bench.status) {
		return EAGAIN;
	}

	if (!res) {
		return EINVAL;
	}

	getrusage(RUSAGE_SELF, &run);
	clock_gettime(RIN_CLOCK_WALL_COUNTER, &wall);

	res->wall = rin_time_sub(&wall, &bench.wall);
	res->system = rin_timeval_sub(&run.ru_stime, &bench.runtime.ru_stime);
	res->user = rin_timeval_sub(&run.ru_utime, &bench.runtime.ru_utime);
	res->total = rin_timeval_add(&res->system, &res->user);

	bench.status = 0;
	return 0;
}