00001 #include "timer.h"
00002 #include <math.h>
00003 #include <stdio.h>
00004 #include <stdlib.h>
00005 #include "exception.h"
00006 Timer::Timer(TimerType type)
00007 {
00008 m_type = type;
00009 msecs= 0;
00010 t0=t1=-1;
00011 }
00012
00013
00017 void Timer::start()
00018 {
00019 if (m_type == PROCESSOR_TIME)
00020 t0=clock();
00021 else if (m_type == CALENDAR_TIME)
00022 t0=time(NULL);
00023 }
00024
00025
00026
00030 void Timer::end()
00031 {
00032 if (t0 == -1)
00033 throw new Exception("Error Timer::end(), call Timer:start() first\n");
00034 if (m_type == PROCESSOR_TIME)
00035 {
00036 t1 = clock();
00037 msecs += ((double ) (t1 - t0))/CLOCKS_PER_SEC*1000;
00038 }
00039 else if (m_type == CALENDAR_TIME)
00040 {
00041 t1 = time(NULL);
00042 }
00043
00044 }
00045
00046 std::string Timer::printTime()
00047 {
00048 char str[200];
00049 if (t1 == -1 || t0 == -1)
00050 {
00051 printf("\nTimer: Nenhum tempo foi marcado. Chame os metodos start() e depois end()");
00052 exit(0);
00053 }
00054 if (m_type == PROCESSOR_TIME)
00055 {
00056 if (msecs == INFINITY)
00057 {
00058 printf("Erro: (printMinutes) Nenhum tempo foi marcado.\nUse o metodo start() e depois end() para marcar o tempo.\n");
00059 exit(1);
00060 }
00061 double rm = msecs;
00062 double min = floor( msecs/60000);
00063 rm = msecs - min*60000;
00064 double secs = floor(rm/1000);
00065 rm = rm - secs*1000;
00066 sprintf(str,"%g:%g:%g",min,secs,rm);
00067 }
00068 else if (m_type == CALENDAR_TIME)
00069 {
00070 int res = t1 -t0;
00071 int hour = res/3600;
00072 int restSec = res%3600;
00073 int minutes = restSec/60;
00074 int secs = restSec%60;
00075 sprintf(str,"%d h:%d m:%d s",hour,minutes,secs);
00076 }
00077 return std::string(str);
00078
00079 }
00080
00081
00082