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