1 /********** 2 TimeCounter.h 3 huangsy13@gmail.com 4 **********/ 5 #ifndef TIMECOUNTER 6 #define TIMECOUNTER 7 8 #include <iostream> 9 #include <cstring> 10 #include <ctime> 11 #include <sstream> 12 #include <cstdlib> 13 #include "FileStruct.h" 14 15 using namespace std; 16 17 struct TimeCounter{ 18 time_t beginT; 19 time_t nowT; 20 int totalTask; 21 int completeTask; 22 string lastUseT; 23 void setUp(int totalTask0){ 24 totalTask = totalTask0; 25 nowT = 0; 26 beginT = time(NULL); 27 } 28 bool update(int taskNow){ 29 nowT = time(NULL); 30 completeTask = taskNow; 31 if (lastUseT == useTime() && completeTask < totalTask){ 32 return false; 33 } 34 else{ 35 lastUseT = useTime(); 36 return true; 37 } 38 } 39 string useTime(){ 40 int r = nowT - beginT; 41 return getTimeStr(r); 42 } 43 string restTime(){ 44 if(completeTask == 0){ 45 return "unknow"; 46 } 47 int restTT = double(totalTask-completeTask)*double(nowT-beginT)/double(completeTask); 48 return getTimeStr(restTT); 49 } 50 string getTimeStr(int r){ 51 int rs = r; 52 int rh = rs/3600; 53 int rm = rs/60; 54 string str; 55 if (rh != 0){ 56 str = numToStr(rh) + " hours "; 57 } 58 if (rs >= 60){ 59 str += numToStr(rm%60) + " minutes "; 60 } 61 str += numToStr(rs%60) + " seconds"; 62 return str; 63 } 64 string percent(){ 65 int p = 100*completeTask/totalTask; 66 return numToStr(p)+"%"; 67 } 68 void print(bool clear){ 69 if (clear) system("clear"); 70 cout << "use time " << useTime()<<endl; 71 cout << "rest Time "<< restTime() <<endl; 72 cout << "complete " << percent() << endl; 73 } 74 void updateAndPrint(int nn,bool clear = true){ 75 if(update(nn)){ 76 print(clear); 77 } 78 } 79 }; 80 81 #endif 82 83 84 /********* 85 main.cpp 86 huangsy13@gmail.com 87 *********/ 88 #include <iostream> 89 #include <cstring> 90 #include <ctime> 91 #include <sstream> 92 #include <cstdlib> 93 #include "TimeCounter.h" 94 95 using namespace std; 96 97 int main(){ 98 TimeCounter T; 99 int totalTask = 5000; 100 T.setUp(totalTask); 101 int taskNow = 0; 102 while(taskNow < totalTask){ 103 T.updateAndPrint(++taskNow); 104 for (int i = 0 ; i < 100000 ; i++){ 105 int a = 50; 106 int b = 100; 107 while(a != b){ 108 a++; 109 } 110 } 111 } 112 }