00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #include <cstdlib>
00025 #include <cstring>
00026 #ifndef WIN32
00027 #include <sys/time.h>
00028 #else // WIN32
00029 #include <sys/types.h>
00030 #include <sys/timeb.h>
00031 #include <windows.h>
00032 #define atoll _atoi64
00033 #endif // WIN32
00034 #include <time.h>
00035 #include <errno.h>
00036 #include <iomanip>
00037 #include <ostream>
00038 #include <sstream>
00039 #include <cassert>
00040 #include "utils.h"
00041
00042 namespace Aseba
00043 {
00046
00047 UnifiedTime::UnifiedTime()
00048 {
00049 #ifndef WIN32
00050 struct timeval tv;
00051 gettimeofday(&tv, NULL);
00052 value = (Value(tv.tv_sec) * 1000) + Value(tv.tv_usec) / 1000;
00053 #else // WIN32
00054 struct __timeb64 tv;
00055 _ftime64_s(&tv);
00056 value = Value(tv.time) * 1000 + Value(tv.millitm);
00057 #endif // WIN32
00058 }
00059
00060 UnifiedTime::UnifiedTime(Value ms) :
00061 value(ms)
00062 {
00063 }
00064
00065 UnifiedTime::UnifiedTime(Value seconds, Value milliseconds) :
00066 value(seconds * 1000 + milliseconds)
00067 {
00068 }
00069
00070 void UnifiedTime::sleep() const
00071 {
00072 #ifndef WIN32
00073 struct timespec ts;
00074 ts.tv_sec = (value / 1000);
00075 ts.tv_nsec = ((value % 1000) * 1000000);
00076 nanosleep(&ts, 0);
00077 #else // WIN32
00078 assert(value < (1 << 32));
00079 Sleep((DWORD)value);
00080 #endif // WIN32
00081 }
00082
00083 std::string UnifiedTime::toHumanReadableStringFromEpoch() const
00084 {
00085 std::ostringstream oss;
00086 Value seconds(value / 1000);
00087 Value milliseconds(value % 1000);
00088 time_t t(seconds);
00089 char *timeString = ctime(&t);
00090 timeString[strlen(timeString) - 1] = 0;
00091 oss << "[";
00092 oss << timeString << " ";
00093 oss << std::setfill('0') << std::setw(3) << milliseconds;
00094 oss << "]";
00095 return oss.str();
00096 }
00097
00098 std::string UnifiedTime::toRawTimeString() const
00099 {
00100 std::ostringstream oss;
00101 Value seconds(value / 1000);
00102 Value milliseconds(value % 1000);
00103 oss << std::dec << seconds << "." << std::setfill('0') << std::setw(3) << milliseconds;
00104 return oss.str();
00105 }
00106
00107 UnifiedTime UnifiedTime::fromRawTimeString(const std::string& rawTimeString)
00108 {
00109 size_t dotPos(rawTimeString.find('.'));
00110 assert(dotPos != std::string::npos);
00111 return UnifiedTime(atoll(rawTimeString.substr(0, dotPos).c_str()), atoll(rawTimeString.substr(dotPos + 1, std::string::npos).c_str()));
00112 }
00113
00114
00115 void dumpTime(std::ostream &stream, bool raw)
00116 {
00117 if (raw)
00118 stream << UnifiedTime().toRawTimeString();
00119 else
00120 stream << UnifiedTime().toHumanReadableStringFromEpoch();
00121 stream << " ";
00122 }
00123
00125 }