]> git.tdb.fi Git - libs/core.git/blob - source/time/utils.cpp
Isolate platform-dependent RawTime conversion functions to a private header
[libs/core.git] / source / time / utils.cpp
1 #ifdef WIN32
2 #include <windows.h>
3 #else
4 #include <sys/resource.h>
5 #include <sys/time.h>
6 #include <cerrno>
7 #endif
8 #include <msp/core/systemerror.h>
9 #include "datetime.h"
10 #include "rawtime_private.h"
11 #include "timedelta.h"
12 #include "timestamp.h"
13 #include "units.h"
14 #include "utils.h"
15
16 using namespace std;
17
18 namespace Msp {
19 namespace Time {
20
21 TimeStamp now()
22 {
23 #ifndef WIN32
24         timeval tv;
25         gettimeofday(&tv, 0);
26         return TimeStamp(tv.tv_sec*1000000LL+tv.tv_usec);
27 #else
28         static RawTime epoch = 0;
29         if(!epoch)
30         {
31                 SYSTEMTIME st;
32                 st.wYear = 1970;
33                 st.wMonth = 1;
34                 st.wDay = 1;
35                 st.wHour = 0;
36                 st.wMinute = 0;
37                 st.wSecond = 0;
38                 st.wMilliseconds = 0;
39
40                 FILETIME ft;
41                 SystemTimeToFileTime(&st, &ft);
42                 epoch = (ft.dwLowDateTime+(static_cast<RawTime>(ft.dwHighDateTime)<<32))/10;
43         }
44         
45         FILETIME ft;
46         GetSystemTimeAsFileTime(&ft);
47         return TimeStamp((ft.dwLowDateTime+(static_cast<RawTime>(ft.dwHighDateTime)<<32))/10-epoch);
48 #endif
49 }
50
51 string format_now(const string &fmt)
52 {
53         return DateTime(now()).format(fmt);
54 }
55
56 TimeDelta get_cpu_time()
57 {
58 #ifndef WIN32
59         rusage ru;
60         getrusage(RUSAGE_SELF, &ru);
61         return (ru.ru_utime.tv_sec+ru.ru_stime.tv_sec)*sec + (ru.ru_utime.tv_usec+ru.ru_stime.tv_usec)*usec;
62 #else
63         //XXX Figure out the function to use on Win32
64         return TimeDelta();
65 #endif
66 }
67
68 void sleep(const TimeDelta &d)
69 {
70 #ifndef WIN32
71         timespec ts = rawtime_to_timespec(d.raw());
72         while(nanosleep(&ts, 0)==-1)
73                 if(errno!=EINTR)
74                         throw system_error("nanosleep");
75 #else
76         Sleep((DWORD)(d/msec));
77 #endif
78 }
79
80 } // namespace Time
81 } // namespace Msp