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