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