]> git.tdb.fi Git - libs/core.git/blob - source/time/utils.cpp
Win32-compatibility
[libs/core.git] / source / time / utils.cpp
1 /*
2 This file is part of libmspframework     
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 "timedelta.h"
13 #include "timestamp.h"
14 #include "units.h"
15 #include "utils.h"
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 int64_t 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+(int64_t)ft.dwHighDateTime<<32)/10;
45         }
46         
47         FILETIME ft;
48         GetSystemTimeAsFileTime(&ft);
49         return TimeStamp((ft.dwLowDateTime+(int64_t)ft.dwHighDateTime<<32)/10-epoch);
50 #endif
51 }
52
53 /**
54 Returns the CPU time used by the program so far.
55 */
56 TimeDelta get_cpu_time()
57 {
58 #ifndef WIN32
59         rusage ru;
60         getrusage(RUSAGE_SELF, &ru);
61         return (ru.ru_utime.tv_sec+ru.ru_stime.tv_sec)*sec + (ru.ru_utime.tv_usec+ru.ru_stime.tv_usec)*usec;
62 #else
63         //XXX Figure out the function to use on Win32
64         return TimeDelta();
65 #endif
66 }
67
68 /**
69 Sleeps for the given time.
70 */
71 int sleep(const TimeDelta &d)
72 {
73 #ifndef WIN32
74         timespec ts;
75         d.fill_timespec(ts);
76         return nanosleep(&ts, 0);
77 #else
78         Sleep(d/msec);
79         return 0;
80 #endif
81 }
82
83 } // namespace Time
84 } // namespace Msp