Measure Run Time of C++ Program

I have a C++ program, and I am going to run it in Linux and try to get the run time of the program. I have to use these particular code in my program.

1
2
  #include <sys/time.h>
   int gettimeofday( struct timeval *tv, struct timezone *tz );


However, I have no idea how to use this. Do I need to also create the function in my program? What do I do or how do I use this to measure the time?
Did you try to google gettimeofday?
http://linux.die.net/man/2/gettimeofday

Calling gettimeofday() returns the following struct:
1
2
3
4
struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};


Declare two structs:
1
2
3
 
  struct timeval start_time;
  struct timeval end_time;


Call the function when your program starts:
 
  gettimeofday(&start_time, NULL);


And again when your program ends:
 
  gettimeofday(&end_time, NULL);


Then compute the difference between the values in the two structs.
I did but I didn't really understand it.

So, do I just put all that code into my program, and then at the end, I would try to print out the difference between the tv_sec of each struct?

Such as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <sys/time.h>
    int main()
    {
         struct timeval start_time;
         struct timeval end_time;

         gettimeofday(&start_time, NULL);
  
         stuff();

          gettimeofday(&end_time, NULL);

         // How do I see the runtime at the end?
         cout << end_time.tv_sec - start_time.tv_sec << endl;

          return 0;
}



Last edited on
That's the general idea, but unless your program runs for more than a second, seconds won't be meaningful. So you probably want to display the difference in microseconds also.
Topic archived. No new replies allowed.