C/C++
Algorithm
Data Structure
UVA Hints
UVA Problem Ranking
Tip and Trick



 

 
Measuring Program Running Time in C/C++-


As programmer, we usually want to measure the speed of our program in time (seconds). C/C++ provides a useful function in timing. We can use the function

clock_t clock(void);

to get the CPU clock time. The idea is simple. Get the starting and the ending CPU clock time then divide by constant CLOCKS_PER_SEC defined in the time.h header file. Don’t forget to put #include <ctime> or <time.h>.

Source Code


#include <iostream>
#include <ctime>
using namespace std;

int main()
{ clock_t start = clock(); // do something // clock_t ends = clock(); cout << "Running Time : " << (double) (ends - start) / CLOCKS_PER_SEC << endl; return 0; }


Creating a Simple Timer Program

We can modify the program above a little bit so that we can have a timer program that measures the speed of the program. In order to create the timer, we should be able to call other program inside our program. This can be done by this useful function

int system(const char *cmd)

which is declared in stdlib.h. Don’t forget to put #include <cstdlib> or <stdlib.h>.

Source Code


#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main(int argc,char **argv)
{
     if (argc != 2)
     {
          // incorrect command line-argument
          cout << "Usage : timer <program_name>" << endl;
          return 1;
     }

     // start the clock
     cout << "Starting" << argv[1] << "..." << endl;
     clock_t start = clock();

     // start program
     system(argv[1]);

     // program ends and stop clock
     clock_t ends = clock();
     cout << "Running Time : " << (double) (ends-start) / CLOCKS_PER_SEC << endl;
     return 0;
}

 






     
Copyright © 2004 - Harvest Software