Generic hardware access library
/home/cschwick/hal/generic/src/linux/common/StopWatch.cc
Go to the documentation of this file.
00001 #include "hal/linux/StopWatch.hh"
00002 #include <sstream>
00003 #include <iomanip>
00004 
00005 HAL::StopWatch::StopWatch( uint32_t laps ) {
00006         lapVector.reserve(laps);
00007         maxLaps = laps;
00008         calibrate();
00009 }
00010 
00011 void HAL::StopWatch::start() {
00012         gettimeofday(&startTime,NULL);
00013 }
00014 
00015 void HAL::StopWatch::stop() {
00016         gettimeofday(&stopTime,NULL);
00017 }
00018 
00019 void HAL::StopWatch::lap() {
00020         gettimeofday( &stopTime,NULL );
00021         lapVector.push_back( stopTime );
00022 }
00023 
00024 uint32_t HAL::StopWatch::read() {
00025         return subtractTime( stopTime, startTime );
00026 }
00027 
00028 uint32_t HAL::StopWatch::readLap( uint32_t lapIndex, std::ostream& os )
00029   throw (IllegalValueException) {
00030         if ( lapIndex > (lapVector.size() - 1) ) {
00031                   std::stringstream text;
00032                   text << "ERROR ===> only " << std::dec << lapVector.size() << "laps taken." << std::ends;
00033                   throw( IllegalValueException( text.str(), __FILE__, __LINE__, __FUNCTION__ )); 
00034         } else if ( lapIndex > maxLaps ) {
00035                 os << "ERROR ===> maximal lap index is " << std::dec << maxLaps << std::endl;
00036                 os << "Measurements might be inprecise due to extra memory allocation" << std::endl;
00037         }
00038         return  subtractTime( lapVector[lapIndex], startTime );
00039 }
00040 
00041 void HAL::StopWatch::reset() {
00042         lapCounter = 0;
00043         lapVector.clear();
00044 }
00045 
00046 void HAL::StopWatch::calibrate() {
00047 
00048 }
00049 
00050 uint32_t HAL::StopWatch::subtractTime(struct timeval& t, struct timeval& sub) {
00051         signed long sec, usec, rsec, rusec;
00052         sec = t.tv_sec - sub.tv_sec;
00053         usec = t.tv_usec - sub.tv_usec;
00054         if (usec < 0) {
00055                 sec--;
00056                 usec += 1000000;
00057   }
00058         if (sec < 0) {
00059                 rsec = 0;
00060                 rusec = 0;
00061         }
00062         else {
00063                 rsec = (uint32_t) sec;
00064                 rusec = (uint32_t) usec;
00065         }
00066         return (rsec * 1000000 + rusec);
00067 }