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