timeUtilities.cpp
Go to the documentation of this file.00001
00015 #include <dlrCommon/exception.h>
00016 #include <dlrPortability/timeUtilities.h>
00017
00018
00019
00020
00021
00022
00023 #ifdef _WIN32
00024
00025
00026
00027 #include <time.h>
00028 #include <windows.h>
00029 #include <sys/timeb.h>
00030
00031
00032
00033 #else
00034
00035
00036
00037 #include <time.h>
00038 #include <sys/time.h>
00039 #include <sys/select.h>
00040
00041
00042
00043 #endif
00044
00045
00046
00047
00048 namespace dlr {
00049
00050 namespace portability {
00051
00052 void preciseSleep(int milliseconds)
00053 {
00054 portableSleep(static_cast<double>(milliseconds) / 1000.0);
00055 }
00056
00057 }
00058
00059 }
00060
00061
00062
00063
00064 #ifdef _WIN32
00065
00066
00067
00068
00069 namespace dlr {
00070
00071 namespace portability {
00072
00073 double
00074 getCurrentTime() {
00075 struct __timeb64 tp;
00076 _ftime64(&tp);
00077 return tp.time + (tp.millitm * 0.001);
00078 }
00079
00080
00081 void
00082 portableSleep(double seconds) {
00083 if(seconds > 0.0) {
00084 int milliseconds = static_cast<int>(1000.0 * seconds + 0.5);
00085 Sleep(milliseconds);
00086 }
00087 }
00088
00089 }
00090
00091 }
00092
00093
00094
00095 #else
00096
00097
00098
00099 #include <cmath>
00100
00101 namespace dlr {
00102
00103 namespace portability {
00104
00105 double
00106 getCurrentTime() {
00107 struct timeval tp;
00108 gettimeofday(&tp, 0);
00109 return tp.tv_sec + (tp.tv_usec * 0.000001);
00110 }
00111
00112
00113 std::string
00114 getISOTimeString(TimeZone timeZone) {
00115
00116 const int bufferSize = 20;
00117 char buffer[bufferSize];
00118 time_t timeSinceEpoch;
00119 time_t returnValue = time(&timeSinceEpoch);
00120 if(returnValue == -1) {
00121 DLR_THROW(RunTimeException, "getISOTimeString()",
00122 "Call to time() failed.");
00123 }
00124 struct tm brokenDownTime;
00125 switch(timeZone) {
00126 case DLR_TZ_GMT:
00127 gmtime_r(&timeSinceEpoch, &brokenDownTime);
00128 break;
00129 case DLR_TZ_LOCAL:
00130 tzset();
00131 localtime_r(&timeSinceEpoch, &brokenDownTime);
00132 break;
00133 default:
00134 DLR_THROW(LogicException, "getISOTimeString()",
00135 "Unexpected value in switch() argument.");
00136 break;
00137 }
00138
00139 strftime(buffer, bufferSize, "%Y-%m-%d %H:%M:%S", &brokenDownTime);
00140 return std::string(buffer);
00141 }
00142
00143
00144 void
00145 portableSleep(double seconds) {
00146 if(seconds > 0.0) {
00147 double integerPart;
00148 double fractionalPart = std::modf(seconds, &integerPart);
00149 struct timeval timeout;
00150 timeout.tv_sec = static_cast<int>(integerPart);
00151 timeout.tv_usec =
00152 static_cast<int>(1000000.0 * fractionalPart + 0.5);
00153 if(timeout.tv_usec == 1000000) {
00154 ++timeout.tv_sec;
00155 timeout.tv_usec = 0;
00156 }
00157 select(0, NULL, NULL, NULL, &timeout);
00158 }
00159 }
00160
00161 }
00162
00163 }
00164
00165
00166
00167 #endif