aboutsummaryrefslogtreecommitdiffstats
path: root/generic/gettime.c
blob: 975457fe755184e09fd0f759b5f0df66b0885b36 (plain) (blame)
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
/*
htop - generic/gettime.c
(C) 2021 htop dev team
Released under the GNU GPLv2+, see the COPYING file
in the source distribution for its full text.
*/
#include "config.h"  // IWYU pragma: keep

#include "generic/gettime.h"

#include <string.h>
#include <time.h>


void Generic_gettime_realtime(struct timeval* tvp, uint64_t* msec) {

#if defined(HAVE_CLOCK_GETTIME)

   struct timespec ts;
   if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
      tvp->tv_sec = ts.tv_sec;
      tvp->tv_usec = ts.tv_nsec / 1000;
      *msec = ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000);
   } else {
      memset(tvp, 0, sizeof(struct timeval));
      *msec = 0;
   }

#else /* lower resolution gettimeofday(2) is always available */

   struct timeval tv;
   if (gettimeofday(&tv, NULL) == 0) {
      *tvp = tv; /* struct copy */
      *msec = ((uint64_t)tv.tv_sec * 1000) + ((uint64_t)tv.tv_usec / 1000);
   } else {
      memset(tvp, 0, sizeof(struct timeval));
      *msec = 0;
   }

#endif
}

void Generic_gettime_monotonic(uint64_t* msec) {
#if defined(HAVE_CLOCK_GETTIME)

   struct timespec ts;
   if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
      *msec = ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000);
   else
      *msec = 0;

#else

# error "No monotonic clock available"

#endif
}

© 2014-2022 Faster IT GmbH | imprint | privacy policy