nmsg  0.9.0
timespec.c
1 /*
2  * Copyright (c) 2008, 2009, 2011-2013 by Farsight Security, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /* Import. */
18 
19 #include "private.h"
20 
21 /* Export. */
22 
23 void
24 nmsg_timespec_get(struct timespec *now) {
25 #ifdef HAVE_CLOCK_GETTIME
26  (void) clock_gettime(CLOCK_REALTIME, now);
27 #else
28  struct timeval tv;
29  (void) gettimeofday(&tv, NULL);
30  now->tv_sec = tv.tv_sec;
31  now->tv_nsec = tv.tv_usec * 1000;
32 #endif
33 }
34 
35 void
36 nmsg_timespec_sleep(const struct timespec *ts) {
37  struct timespec rqt, rmt;
38 
39  for (rqt = *ts; nanosleep(&rqt, &rmt) < 0 && errno == EINTR; rqt = rmt)
40  ;
41 }
42 
43 void
44 nmsg_timespec_add(const struct timespec *a, struct timespec *b) {
45  b->tv_sec += a->tv_sec;
46  b->tv_nsec += a->tv_nsec;
47  while (b->tv_nsec >= NMSG_NSEC_PER_SEC) {
48  b->tv_sec += 1;
49  b->tv_nsec -= NMSG_NSEC_PER_SEC;
50  }
51 }
52 
53 void
54 nmsg_timespec_sub(const struct timespec *a, struct timespec *b) {
55  b->tv_sec -= a->tv_sec;
56  b->tv_nsec -= a->tv_nsec;
57  if (b->tv_nsec < 0) {
58  b->tv_sec -= 1;
59  b->tv_nsec += NMSG_NSEC_PER_SEC;
60  }
61 }
62 
63 double
64 nmsg_timespec_to_double(const struct timespec *ts) {
65  return (ts->tv_sec + ts->tv_nsec / 1E9);
66 }
67 
68 void
69 nmsg_timespec_from_double(double seconds, struct timespec *ts) {
70  ts->tv_sec = (time_t) seconds;
71  ts->tv_nsec = (long) ((seconds - ((int) seconds)) * 1E9);
72 }
void nmsg_timespec_get(struct timespec *ts)
Get the current time.
Definition: timespec.c:24
void nmsg_timespec_from_double(double seconds, struct timespec *ts)
Convert floating point number of seconds to timespec.
Definition: timespec.c:69
void nmsg_timespec_add(const struct timespec *a, struct timespec *b)
Add timespecs a and b, placing result in b.
Definition: timespec.c:44
double nmsg_timespec_to_double(const struct timespec *ts)
Convert timespec to floating point representation.
Definition: timespec.c:64
void nmsg_timespec_sleep(const struct timespec *ts)
Sleep.
Definition: timespec.c:36
void nmsg_timespec_sub(const struct timespec *a, struct timespec *b)
Subtract timespec b from a, placing result in b.
Definition: timespec.c:54