Tag Archives: Clock
C++ || Snippet – Simple Timer Class Using The Clock Function
The following is sample code for a simple timer class using the “clock()” function. The “clock” function returns the processor time that has been consumed by the program during its execution; or in other words, it returns the number of clock ticks that has elapsed since the program was launched.
The timer class demonstrated on this page has the ability to measure the execution time of a block of code or function call, and display the elapsed running time (in seconds) to the screen.
Unfortunately, by using the clock() function (instead of date based methods) to measure time, this class is only able to measure the time that was actually spent used by the CPU during the execution of the program. That means that if this timer class was used to measure how long it took for a user to enter data into the program, the users CPU wouldn’t notice any change in time, and this timer class would display that 0 seconds had elapsed.
However, by using the clock() function to measure elapsed time, it can be used to implement a simple and portable timer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
// ============================================================================ // Author: K Perkins // Date: Jul 22, 2013 // Taken From: http://programmingnotes.org/ // File: Timer.h // Description: This is a simple timer class using the "clock" function. // ============================================================================ #ifndef TIMER_H #define TIMER_H #include <cassert> #include <ctime> class Timer { public: Timer(); /* Function: Constructor initializes data Precondition: None Postcondition: Defines private variables */ void Start(); /* Function: Starts the timer Precondition: Timer has been initialized Postcondition: Timer has been started */ void Stop(); /* Function: Stops the timer Precondition: Timer has been initialized Postcondition: Timer has been stopped */ void Reset(); /* Function: Resets the clock Precondition: Timer has been initialized Postcondition: Timer has been restarted */ double Timestamp() const; /* Function: Returns the amount of time (in seconds) that has elapsed since the clock has started. Precondition: The timer has been started but does not need to be stopped. The timer continues to run Postcondition: The total time since the clock started is returned */ double Elapsed() const; /* Function: Returns the amount of time (in seconds) that has elapsed since the clock has started. Precondition: The timer has been started and must be stopped Postcondition: The total elapsed time after the clock has stopped is returned */ private: clock_t m_start; // the first reading by the clock clock_t m_end; // the last reading by the clock }; #endif //========================= Implementation ================================// Timer::Timer() { Reset(); }// end of Timer void Timer::Start() { m_start = clock(); }// end of Start void Timer::Stop() { m_end = clock(); }// end of Stop void Timer::Reset() { m_start = 0; m_end = 0; }// end of Reset double Timer::Timestamp() const { clock_t temp = clock(); assert(temp >= m_start); return (double)(temp-m_start)/((double)CLOCKS_PER_SEC); }// end of Timestamp double Timer::Elapsed() const { assert(m_end >= m_start); return (double)(m_end-m_start)/((double)CLOCKS_PER_SEC); }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
===== DEMONSTRATION HOW TO USE =====
Use of the above class is very simple to use. Here are sample programs demonstrating its use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
#include <iostream> #include <cstdlib> #include <ctime> #include <algorithm> #include "Timer.h" using namespace std; // function prototype void Display(int arry[], int size); // constant variable const int SIZE = 10000000; int main() { // declare variables srand(time(NULL)); Timer timer; int* arry = new int[SIZE]; // place random numbers into the array for(int x = 0; x < SIZE; ++x) { arry[x] = rand()%1000+1; } // display array data if within range if(SIZE <= 20) { cout<<"Original array values:n"; Display(arry, SIZE); } cerr<<"nStarting the timer.."; // start the timer timer.Start(); // sort the array using the built in function std::sort(arry, arry+SIZE); // stop the timer timer.Stop(); cout<<"nTimer stopped!n"; // display array data if within range if(SIZE <= 20) { cout<<"nThe current sorted array:n"; Display(arry, SIZE); } // display the elapsed time cout<<"nIt took "<<timer.Elapsed()*1000 <<" clicks ("<<timer.Elapsed()<<" seconds)"<<endl; return 0; }// end of main void Display(int arry[], int size) { for(int x = 0; x < size; ++x) { cout<<arry[x]<<" "; } cout<<"n"; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Starting the timer..
Timer stopped!It took 3749 clicks (3.749 seconds)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> #include "Timer.h" using namespace std; int main() { // declare variables Timer timer; int sleep = 0; int elapsedtime = 0; // ask user how long they want to sleep cout<< "How many seconds do you want to sleep?: "; cin >> sleep; cerr<<"nStarting the timer..n"; // start the timer timer.Start(); // use a loop to sleep while((int)timer.Timestamp() < sleep) { if((int)timer.Timestamp() == elapsedtime) { cout<<elapsedtime++<<endl; } } // stop the timer timer.Stop(); cout<<"naTimer stopped!n"; // display the elapsed time cout<<"nIt took "<<timer.Elapsed()*1000 <<" clicks ("<<timer.Elapsed()<<" seconds)"<<endl; return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
How many seconds do you want to sleep?: 5
Starting the timer..
0
1
2
3
4Timer stopped!
It took 5000 clicks (5 seconds)
C++ || Struct – Add One Second To The Clock Using A Struct
Here is another actual homework assignment which was presented in an intro to programming class. This program utilizes a struct, which is very similar to the class concept. For this assignment, the class was asked to make a program which prompted the user to enter a time in HH:MM:SS (Hours:Minutes:Seconds) format. Upon obtaining the time from the user, our class was asked to use a struct implementation which was to simply add one second to the time that was entered by the user. Seems easy enough, though I initially had afew problems when starting the program.
This page will be very brief in its breakdown of the program’s code, as it is already heavily commented. The code is basically unchanged from the code which was turned in for grading.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Functions
Passing a Value By Reference
Structures
Constant Variables
Boolean Expressions
Setw
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
// ============================================================================ // File: AddOneSecond.cpp // ============================================================================ // Description: // This program prompts the user for the input time, then adds // one second to the time -- if any of the time structure fields need to // "rollover" (e.g., the hours, minutes or seconds need to be reset to zero), // this function will handle that. Finally, the incremented time will be // displayed to stdout. // ============================================================================ #include <iostream> #include <iomanip> using namespace std; // structure declaration struct Time { int hours; int min; int sec; }; // defined constants which do not change // specifies the max values for each variable const int MAX_HOURS = 23; const int MAX_MINS = 59; const int MAX_SECS = 59; // function prototypes bool IsTimeValid(Time timeParam); void AddOneSecond(Time &timeParam); void DisplayTime(Time timeParam); // ==== main ================================================================== // // ============================================================================ int main() { Time userTime = {0,0,0}; // Initialize struct members: hrs, min, sec to 0 char colon = ':'; cout << "Please enter the time in HH:MM:SS format: "; cin >> userTime.hours >> colon >> userTime.min >> colon >> userTime.sec; // Checks to see if user entered correct data if (IsTimeValid(userTime) == false) { cout << "Invalid input...n" << endl; exit(EXIT_FAILURE); } cout << "nThe incremented time is "; AddOneSecond(userTime); DisplayTime(userTime); return 0; } // end of main // ==== IsTimeValid =========================================================== // // This function will validate that the time structure contains legitimate // values. If this function determines that the time values are invalid, it // will display an error message to stdout. // // Input: // limit [IN] -- The users time input // // Output: // The Time structure as an argument to the AddOneSecond function // // ============================================================================ bool IsTimeValid(Time timeParam) { // checks to see if user inputted data falls between the specified // const variables as declared above if ((timeParam.hours >= 0 && timeParam.hours <= MAX_HOURS) &&(timeParam.min >= 0 && timeParam.min <= MAX_MINS) &&(timeParam.sec >= 0 && timeParam.sec <= MAX_SECS)) { return true; } else { return false; } } // end of IsTimeValid // ==== AddOneSecond ========================================================== // // This function will add one second to the time // // Input: // limit [IN] -- The users time input // // Output: // The incremented time will be displayed to stdout by calling the // DisplayTime function // // ============================================================================ void AddOneSecond(Time &timeParam) { // this is just a simple bool which checks to see if // the program should increment the max hrs in the // 1st or 2nd if statements, which are located below bool incrementHrsInFirstIf = false; // this is just a simple bool which checks to see if // the program should increment the max mins in the // 2nd or 3rd if statements, which are located below bool incrementMinInSecondIf = false; // ========== if statement #1 - hrs ========== // checks to see if user selected hrs is equal to MAX // if it is, reset time back to 0 if (timeParam.hours == MAX_HOURS && timeParam.min == MAX_MINS) { timeParam.hours = 0; incrementHrsInFirstIf = true; } // ========== if statement #2 - min ========== // checks to see if user selected mins is equal to MAX // if it is, reset time back to 0 if (timeParam.min == MAX_MINS) { timeParam.min = 0; // if mins == 59, we need to increment the hrs by 1 if(incrementHrsInFirstIf == false) { ++timeParam.hours; } incrementMinInSecondIf = true; } // ========== if statement #3 - Secs ========== // checks to see if user selected sec is equal to MAX // if it is, reset time back to 0 if (timeParam.sec == MAX_SECS) { timeParam.sec = 0; // if secs == 59, we need to increment the mins by 1 if(incrementMinInSecondIf == false) { ++timeParam.min; } } else // if time is not at max, increment by 1 { ++timeParam.sec; } } // end of AddOneSecond // ==== DisplayTime =========================================================== // // This function will display the user's time // // Input: // limit [IN] -- The users time input // // Output: // The incremented time will be displayed // // ============================================================================ void DisplayTime(Time timeParam) { cout.fill('0'); cout << setw(2) << timeParam.hours << ":" << setw(2) << timeParam.min << ":" << setw(2) << timeParam.sec << endl; } // http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
STRUCT
The structure declaration is placed above the main function, as noted on lines 16-21, containing the 3 variables (Hrs, min, sec) which are defined within the program. Line 39 displays how to access those variables from the main function, having the variable “Time userTime” as the means of access. Note, line 43, the variables can utilize cin for input.
CONST
Lines 25-27 declare the constant variables, which hold the maximum allowable time the clock is able to display. The function IsTimeValid (line 72) checks to see if user defined input is within the maximum allowable limit or not.
FILL
The program will automatically display 2 numbers for hours,mins,sec even if the user only inputted one number, as noted on lines 169-172. This is basically the same as the setfill function.
Once compiling the above code, you should receive this as your output
Note: The code was compiled five separate times to display the different outputs its able to produce
==== SAMPLE RUN #1 ====
Please enter the time in HH:MM:SS format: 0:0:25
The incremented time is 00:00:26==== SAMPLE RUN #2 ====
Please enter the time in HH:MM:SS format: 23:58:59
The incremented time is 23:59:00==== SAMPLE RUN #3 ====
Please enter the time in HH:MM:SS format: 23:59:59
The incremented time is 00:00:00==== SAMPLE RUN #4 ====
Please enter the time in HH:MM:SS format: : :
The incremented time is 00:00:01==== SAMPLE RUN #5 ====
Please enter the time in HH:MM:SS format: 76:09:67
Invalid input...