]> git.tdb.fi Git - libs/core.git/blob - source/time/utils.cpp
Clean up after the timedelta.h/units.h merge
[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 "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(timeval_to_rawtime(tv));
26 #else
27         FILETIME ft;
28         GetSystemTimeAsFileTime(&ft);
29         return TimeStamp(filetime_to_rawtime(ft));
30 #endif
31 }
32
33 string format_now(const string &fmt)
34 {
35         return DateTime(now()).format(fmt);
36 }
37
38 TimeDelta get_cpu_time()
39 {
40 #ifndef WIN32
41         rusage ru;
42         getrusage(RUSAGE_SELF, &ru);
43         return (ru.ru_utime.tv_sec+ru.ru_stime.tv_sec)*sec + (ru.ru_utime.tv_usec+ru.ru_stime.tv_usec)*usec;
44 #else
45         //XXX Figure out the function to use on Win32
46         return TimeDelta();
47 #endif
48 }
49
50 void sleep(const TimeDelta &d)
51 {
52 #ifndef WIN32
53         timespec ts = rawtime_to_timespec(d.raw());
54         while(nanosleep(&ts, 0)==-1)
55                 if(errno!=EINTR)
56                         throw system_error("nanosleep");
57 #else
58         Sleep((DWORD)(d/msec));
59 #endif
60 }
61
62 } // namespace Time
63 } // namespace Msp