Fix: use lttng_clock_gettime instead of clock_gettime
[lttng-tools.git] / tests / utils / utils.c
1 /*
2 * Copyright (C) - 2015 Jérémie Galarneau <jeremie.galarneau@efficios.com>
3 *
4 * This library is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License as published by the
6 * Free Software Foundation; version 2.1 of the License.
7 *
8 * This library is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
11 * for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this library; if not, write to the Free Software Foundation,
15 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16 */
17
18 #include <stdint.h>
19 #include <common/compat/time.h>
20 #include <common/time.h>
21 #include <assert.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <errno.h>
25
26 static inline
27 int64_t elapsed_time_ns(struct timespec *t1, struct timespec *t2)
28 {
29 struct timespec delta;
30
31 assert(t1 && t2);
32 delta.tv_sec = t2->tv_sec - t1->tv_sec;
33 delta.tv_nsec = t2->tv_nsec - t1->tv_nsec;
34 return ((int64_t) NSEC_PER_SEC * (int64_t) delta.tv_sec) +
35 (int64_t) delta.tv_nsec;
36 }
37
38 int usleep_safe(useconds_t usec)
39 {
40 int ret = 0;
41 struct timespec t1, t2;
42 int64_t time_remaining_ns = (int64_t) usec * (int64_t) NSEC_PER_USEC;
43
44 ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t1);
45 if (ret) {
46 ret = -1;
47 perror("clock_gettime");
48 goto end;
49 }
50
51 while (time_remaining_ns > 0) {
52 ret = usleep(time_remaining_ns / (int64_t) NSEC_PER_USEC);
53 if (ret && errno != EINTR) {
54 perror("usleep");
55 goto end;
56 }
57
58 ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t2);
59 if (ret) {
60 perror("clock_gettime");
61 goto end;
62 }
63
64 time_remaining_ns -= elapsed_time_ns(&t1, &t2);
65 }
66 end:
67 return ret;
68 }
This page took 0.032751 seconds and 6 git commands to generate.