WvStreams
wvtimeutils.cc
1 /*
2  * Worldvisions Weaver Software:
3  * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
4  *
5  * Various little time functions...
6  */
7 #include "wvtimeutils.h"
8 #include <limits.h>
9 #ifndef _MSC_VER
10 #include <unistd.h>
11 #include <utime.h>
12 #endif
13 
14 time_t msecdiff(const WvTime &a, const WvTime &b)
15 {
16  long long secdiff = a.tv_sec - b.tv_sec;
17  long long usecdiff = a.tv_usec - b.tv_usec;
18  long long msecs = secdiff * 1000 + usecdiff / 1000;
19 
20  time_t rval;
21  if (msecs > INT_MAX)
22  rval = INT_MAX;
23  else if (msecs < INT_MIN)
24  rval = INT_MIN;
25  else
26  rval = msecs;
27  return rval;
28 }
29 
30 
31 WvTime wvtime()
32 {
33  struct timeval tv;
34  gettimeofday(&tv, 0);
35  return tv;
36 }
37 
38 
39 WvTime msecadd(const WvTime &a, time_t msec)
40 {
41  WvTime b;
42  b.tv_sec = a.tv_sec + msec / 1000;
43  b.tv_usec = a.tv_usec + (msec % 1000) * 1000;
44  normalize(b);
45  return b;
46 }
47 
48 
49 WvTime tvdiff(const WvTime &a, const WvTime &b)
50 {
51  WvTime c;
52  c.tv_sec = a.tv_sec - b.tv_sec;
53  c.tv_usec = a.tv_usec;
54 
55  if (b.tv_usec > a.tv_usec)
56  {
57  c.tv_sec--;
58  c.tv_usec += 1000000;
59  }
60 
61  c.tv_usec -= b.tv_usec;
62 
63  normalize(c);
64  return c;
65 }
66 
67 
68 static WvTime wvstime_cur = wvtime();
69 
70 
71 const WvTime &wvstime()
72 {
73  return wvstime_cur;
74 }
75 
76 
77 static void do_wvstime_sync(bool forward_only)
78 {
79  if (!forward_only)
80  {
81  wvstime_cur = wvtime();
82  }
83  else
84  {
85  WvTime now = wvtime();
86  if (wvstime_cur < now)
87  wvstime_cur = now;
88  }
89 }
90 
91 
92 void wvstime_sync()
93 {
94  do_wvstime_sync(false);
95 }
96 
97 
98 void wvstime_sync_forward()
99 {
100  do_wvstime_sync(true);
101 }
102 
103 
104 void wvstime_set(const WvTime &_new_time)
105 {
106  wvstime_cur = _new_time;
107 }
108 
109 
110 void wvdelay(int msec_delay)
111 {
112 #ifdef _WIN32
113  Sleep(msec_delay);
114 #else
115  usleep(msec_delay * 1000);
116 #endif
117 }
WvTime
Based on (and interchangeable with) struct timeval.
Definition: wvtimeutils.h:17