target: Do not use LOG_USER() for error messages
[openocd.git] / src / helper / time_support.c
blobdda3cb3e4e1b382523a38efc53cc43896bfd829d
1 // SPDX-License-Identifier: GPL-2.0-or-later
3 /***************************************************************************
4 * Copyright (C) 2006 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 * *
7 * Copyright (C) 2007,2008 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 * *
10 * Copyright (C) 2008 by Spencer Oliver *
11 * spen@spen-soft.co.uk *
12 ***************************************************************************/
14 #ifdef HAVE_CONFIG_H
15 #include "config.h"
16 #endif
18 #include "time_support.h"
20 /* calculate difference between two struct timeval values */
21 int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
23 if (x->tv_usec < y->tv_usec) {
24 int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
25 y->tv_usec -= 1000000 * nsec;
26 y->tv_sec += nsec;
28 if (x->tv_usec - y->tv_usec > 1000000) {
29 int nsec = (x->tv_usec - y->tv_usec) / 1000000;
30 y->tv_usec += 1000000 * nsec;
31 y->tv_sec -= nsec;
34 result->tv_sec = x->tv_sec - y->tv_sec;
35 result->tv_usec = x->tv_usec - y->tv_usec;
37 /* Return 1 if result is negative. */
38 return x->tv_sec < y->tv_sec;
41 int timeval_add_time(struct timeval *result, long sec, long usec)
43 result->tv_sec += sec;
44 result->tv_usec += usec;
46 while (result->tv_usec > 1000000) {
47 result->tv_usec -= 1000000;
48 result->tv_sec++;
51 return 0;
54 /* compare two timevals and return -1/0/+1 accordingly */
55 int timeval_compare(const struct timeval *x, const struct timeval *y)
57 if (x->tv_sec < y->tv_sec)
58 return -1;
59 else if (x->tv_sec > y->tv_sec)
60 return 1;
61 else if (x->tv_usec < y->tv_usec)
62 return -1;
63 else if (x->tv_usec > y->tv_usec)
64 return 1;
65 else
66 return 0;
69 int duration_start(struct duration *duration)
71 return gettimeofday(&duration->start, NULL);
74 int duration_measure(struct duration *duration)
76 struct timeval end;
77 int retval = gettimeofday(&end, NULL);
78 if (retval == 0)
79 timeval_subtract(&duration->elapsed, &end, &duration->start);
80 return retval;
83 float duration_elapsed(const struct duration *duration)
85 float t = duration->elapsed.tv_sec;
86 t += (float)duration->elapsed.tv_usec / 1000000.0;
87 return t;
90 float duration_kbps(const struct duration *duration, size_t count)
92 return count / (1024.0 * duration_elapsed(duration));