00001
00002
00003
00004
00005
00006
00007 #include "SgSystem.h"
00008 #include "SgTime.h"
00009
00010 #include <cstring>
00011 #include <ctime>
00012 #include <iomanip>
00013 #include <limits>
00014 #include <iostream>
00015 #include <sstream>
00016 #include <errno.h>
00017 #include <sys/time.h>
00018 #include <sys/times.h>
00019 #include <unistd.h>
00020 #include "SgException.h"
00021
00022 using namespace std;
00023
00024
00025
00026 namespace {
00027
00028 SgTimeMode g_defaultMode = SG_TIME_REAL;
00029
00030 bool g_isInitialized = false;
00031
00032 clock_t g_ticksPerSecond;
00033
00034 clock_t g_ticksPerMinute;
00035
00036 void Init()
00037 {
00038 int ticksPerSecond = sysconf(_SC_CLK_TCK);
00039 if (ticksPerSecond < 0)
00040 {
00041 throw SgException("Could not get _SC_CLK_TCK.");
00042 }
00043 g_ticksPerSecond = static_cast<clock_t>(ticksPerSecond);
00044 g_ticksPerMinute = 60 * g_ticksPerSecond;
00045 g_isInitialized = true;
00046 }
00047
00048 }
00049
00050
00051
00052 string SgTime::Format(double time, bool minsAndSecs)
00053 {
00054 ostringstream out;
00055 if (minsAndSecs)
00056 {
00057 int mins = static_cast<int>(time / 60);
00058 int secs = static_cast<int>(time - mins * 60);
00059 out << setw(2) << mins << ':' << setw(2) << setfill('0')
00060 << secs;
00061 }
00062 else
00063 out << setprecision(2) << fixed << time;
00064 return out.str();
00065 }
00066
00067 double SgTime::Get()
00068 {
00069 return Get(g_defaultMode);
00070 }
00071
00072 double SgTime::Get(SgTimeMode mode)
00073 {
00074 if (! g_isInitialized)
00075 Init();
00076 switch (mode)
00077 {
00078 case SG_TIME_CPU:
00079 {
00080 struct tms buf;
00081 if (times(&buf) == static_cast<clock_t>(-1))
00082 {
00083 std::cerr << "Time measurement overflow.\n";
00084 return 0;
00085 }
00086 clock_t clockTicks =
00087 buf.tms_utime + buf.tms_stime
00088 + buf.tms_cutime + buf.tms_cstime;
00089 return static_cast<double>(clockTicks) / g_ticksPerSecond;
00090 }
00091 case SG_TIME_REAL:
00092 {
00093 struct timeval timeVal;
00094 if (gettimeofday(&timeVal, 0) != 0)
00095 throw SgException(string("gettimeofday: ") + strerror(errno));
00096 return (timeVal.tv_sec
00097 + static_cast<double>(timeVal.tv_usec) / 1e6);
00098 }
00099 default:
00100 SG_ASSERT(false);
00101 return 0;
00102 }
00103 }
00104
00105 SgTimeMode SgTime::DefaultMode()
00106 {
00107 return g_defaultMode;
00108 }
00109
00110 void SgTime::SetDefaultMode(SgTimeMode mode)
00111 {
00112 g_defaultMode = mode;
00113 }
00114
00115 string SgTime::TodaysDate()
00116 {
00117 time_t systime = time(0);
00118 struct tm* currtime = localtime(&systime);
00119 const int BUF_SIZE = 14;
00120 char buf[BUF_SIZE];
00121 strftime(buf, BUF_SIZE - 1, "%Y-%m-%d", currtime);
00122 return string(buf);
00123 }
00124
00125
00126