00001 00005 #include "Time.h" 00006 #include <errno.h> 00007 #ifdef _WIN32 00008 #include <windows.h> 00009 #else 00010 #ifdef __linux 00011 #include <time.h> 00012 #endif 00013 #include <sys/time.h> 00014 #endif 00015 #include <iostream> 00016 #include <cstdlib> 00017 using namespace std; 00018 00019 static bool initialized = false; 00020 #ifdef _WIN32 00021 static LARGE_INTEGER frequency; 00022 static LARGE_INTEGER start_time; 00023 #else 00024 static struct timeval start_time; 00025 #endif 00026 00027 void 00028 Time::initialize() 00029 { 00030 initialized=true; 00031 #ifdef _WIN32 00032 if ( !QueryPerformanceFrequency( &frequency ) ) { 00033 cerr << "QueryPerformanceFrequency failed" << endl; 00034 exit( 1 ); 00035 } 00036 if ( !QueryPerformanceCounter( &start_time ) ) { 00037 cerr << "QueryPerformanceCounter failed" << endl; 00038 exit( 1 ); 00039 } 00040 #else 00041 if(gettimeofday(&start_time, 0) != 0) { 00042 cerr << "gettimeofday failed: " << strerror(errno) << endl; 00043 exit( 1 ); 00044 } 00045 #endif 00046 } 00047 00048 double Time::currentSeconds() 00049 { 00050 if(!initialized) 00051 initialize(); 00052 #ifdef _WIN32 00053 LARGE_INTEGER now_time; 00054 if ( !QueryPerformanceCounter( &now_time ) ) { 00055 cerr << "QueryPerformanceCounter failed" << endl; 00056 exit( 1 ); 00057 } 00058 return static_cast< double >(now_time.QuadPart - start_time.QuadPart) / frequency.QuadPart; 00059 #else 00060 struct timeval now_time; 00061 if(gettimeofday(&now_time, 0) != 0) { 00062 cerr << "gettimeofday failed: " << strerror(errno) << endl; 00063 exit( 1 ); 00064 } 00065 return (now_time.tv_sec-start_time.tv_sec)+(now_time.tv_usec-start_time.tv_usec)*1.e-6; 00066 #endif 00067 }