WvStreams
wvtimeutils.cc
00001 /*
00002  * Worldvisions Weaver Software:
00003  *   Copyright (C) 1997-2002 Net Integration Technologies, Inc.
00004  *
00005  * Various little time functions...
00006  */
00007 #include "wvtimeutils.h"
00008 #include <limits.h>
00009 #ifndef _MSC_VER
00010 #include <unistd.h>
00011 #include <utime.h>
00012 #endif
00013 
00014 time_t msecdiff(const WvTime &a, const WvTime &b)
00015 {
00016     long long secdiff = a.tv_sec - b.tv_sec;
00017     long long usecdiff = a.tv_usec - b.tv_usec;
00018     long long msecs = secdiff * 1000 + usecdiff / 1000;
00019 
00020     time_t rval;
00021     if (msecs > INT_MAX)
00022         rval = INT_MAX;
00023     else if (msecs < INT_MIN)
00024         rval = INT_MIN;
00025     else
00026         rval = msecs;
00027     return rval;
00028 }
00029 
00030 
00031 WvTime wvtime()
00032 {
00033     struct timeval tv;
00034     gettimeofday(&tv, 0);
00035     return tv;
00036 }
00037 
00038 
00039 WvTime msecadd(const WvTime &a, time_t msec)
00040 {
00041     WvTime b;
00042     b.tv_sec = a.tv_sec + msec / 1000;
00043     b.tv_usec = a.tv_usec + (msec % 1000) * 1000;
00044     normalize(b);
00045     return b;
00046 }
00047 
00048 
00049 WvTime tvdiff(const WvTime &a, const WvTime &b)
00050 {
00051     WvTime c;
00052     c.tv_sec = a.tv_sec - b.tv_sec;
00053     c.tv_usec = a.tv_usec;
00054 
00055     if (b.tv_usec > a.tv_usec)
00056     {
00057         c.tv_sec--;
00058         c.tv_usec += 1000000;
00059     }
00060 
00061     c.tv_usec -= b.tv_usec;
00062 
00063     normalize(c);
00064     return c;
00065 }
00066 
00067 
00068 static WvTime wvstime_cur = wvtime();
00069 
00070 
00071 const WvTime &wvstime()
00072 {
00073     return wvstime_cur;
00074 }
00075 
00076 
00077 static void do_wvstime_sync(bool forward_only)
00078 {
00079     if (!forward_only)
00080     {
00081         wvstime_cur = wvtime();
00082     }
00083     else
00084     {
00085         WvTime now = wvtime();
00086         if (wvstime_cur < now)
00087             wvstime_cur = now;
00088     }
00089 }
00090 
00091 
00092 void wvstime_sync()
00093 {
00094     do_wvstime_sync(false);
00095 }
00096 
00097 
00098 void wvstime_sync_forward()
00099 {
00100     do_wvstime_sync(true);
00101 }
00102 
00103 
00104 void wvstime_set(const WvTime &_new_time)
00105 {
00106     wvstime_cur = _new_time;
00107 }
00108 
00109 
00110 void wvdelay(int msec_delay)
00111 {
00112 #ifdef _WIN32
00113     Sleep(msec_delay);
00114 #else
00115     usleep(msec_delay * 1000);
00116 #endif
00117 }