]> git.tdb.fi Git - libs/core.git/blob - source/time/utils.cpp
Drop copyright and license notices from source files
[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 #endif
7 #include "datetime.h"
8 #include "timedelta.h"
9 #include "timestamp.h"
10 #include "units.h"
11 #include "utils.h"
12
13 using namespace std;
14
15 namespace Msp {
16 namespace Time {
17
18 /**
19 Returns the current timestamp.
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 /**
57 Returns the CPU time used by the program so far.
58 */
59 TimeDelta get_cpu_time()
60 {
61 #ifndef WIN32
62         rusage ru;
63         getrusage(RUSAGE_SELF, &ru);
64         return (ru.ru_utime.tv_sec+ru.ru_stime.tv_sec)*sec + (ru.ru_utime.tv_usec+ru.ru_stime.tv_usec)*usec;
65 #else
66         //XXX Figure out the function to use on Win32
67         return TimeDelta();
68 #endif
69 }
70
71 /**
72 Sleeps for the given time.
73 */
74 int sleep(const TimeDelta &d)
75 {
76 #ifndef WIN32
77         timespec ts = d;
78         return nanosleep(&ts, 0);
79 #else
80         Sleep((DWORD)(d/msec));
81         return 0;
82 #endif
83 }
84
85 } // namespace Time
86 } // namespace Msp