]> git.tdb.fi Git - libs/core.git/blob - source/time/utils.cpp
ad0d24550338f7c22117057a2354d42f93e6c09e
[libs/core.git] / source / time / utils.cpp
1 /*
2 This file is part of libmspcore     
3 Copyright © 2006  Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
5 */
6 #ifdef WIN32
7 #include <windows.h>
8 #else
9 #include <sys/resource.h>
10 #include <sys/time.h>
11 #endif
12 #include "datetime.h"
13 #include "timedelta.h"
14 #include "timestamp.h"
15 #include "units.h"
16 #include "utils.h"
17
18 using namespace std;
19
20 namespace Msp {
21 namespace Time {
22
23 /**
24 Returns the current timestamp.
25 */
26 TimeStamp now()
27 {
28 #ifndef WIN32
29         timeval tv;
30         gettimeofday(&tv, 0);
31         return TimeStamp(tv.tv_sec*1000000LL+tv.tv_usec);
32 #else
33         static int64_t epoch=0;
34         if(!epoch)
35         {
36                 SYSTEMTIME st;
37                 st.wYear=1970;
38                 st.wMonth=1;
39                 st.wDay=1;
40                 st.wHour=0;
41                 st.wMinute=0;
42                 st.wSecond=0;
43                 st.wMilliseconds=0;
44
45                 FILETIME ft;
46                 SystemTimeToFileTime(&st, &ft);
47                 epoch=(ft.dwLowDateTime+(int64_t)ft.dwHighDateTime<<32)/10;
48         }
49         
50         FILETIME ft;
51         GetSystemTimeAsFileTime(&ft);
52         return TimeStamp((ft.dwLowDateTime+(int64_t)ft.dwHighDateTime<<32)/10-epoch);
53 #endif
54 }
55
56 string format_now(const string &fmt)
57 {
58         return DateTime(now()).format(fmt);
59 }
60
61 /**
62 Returns the CPU time used by the program so far.
63 */
64 TimeDelta get_cpu_time()
65 {
66 #ifndef WIN32
67         rusage ru;
68         getrusage(RUSAGE_SELF, &ru);
69         return (ru.ru_utime.tv_sec+ru.ru_stime.tv_sec)*sec + (ru.ru_utime.tv_usec+ru.ru_stime.tv_usec)*usec;
70 #else
71         //XXX Figure out the function to use on Win32
72         return TimeDelta();
73 #endif
74 }
75
76 /**
77 Sleeps for the given time.
78 */
79 int sleep(const TimeDelta &d)
80 {
81 #ifndef WIN32
82         timespec ts;
83         d.fill_timespec(ts);
84         return nanosleep(&ts, 0);
85 #else
86         Sleep((DWORD)(d/msec));
87         return 0;
88 #endif
89 }
90
91 } // namespace Time
92 } // namespace Msp