C++
Code Warrior
Miscellaneous Tips



Time

C++ has a standard library named time.h.

It defines a class named time_t.

Defined constants:

NULL = 0;


Functions:


time(NULL) //always use NULL

usage:

time_t sec;                    //create a time object named sec;
sec = time(NULL);     //store the number of seconds since 12:00 AM that began January 1, 1980.

difftime(t2,t1); //returns number of seconds (type int) elapsed from t1 to t2 (both of type time_t, t1 is the EARLIER time).

usage:
int elapse = difftime(t2,t1);        //store seconds elapsed from t1 to t2 in variable elapse.

putting it all together

Sample:

#include <time.h>

time_t Start_t, End_t;
int time_task1, time_task2;

Start_t = time(NULL);    //record time that task 1 begins
//perform task 1 here
End_t = time(NULL);    //record time that task 1 ends
time_task1 = difftime(End_t, Start_t);    //compute elapsed time of task 1

Start_t = time(NULL);    //record time that task 2 begins
//perform task 2 here
End_t = time(NULL);    //record time that task 2 ends
time_task2 = difftime(End_t, Start_t);   //compute elapsed time of task 2

cout << "Task 1 took " << setw(3) << time_task1 << " seconds.\n";
cout << "Task 2 took " << setw(3) << time_task2 << " seconds.\n";



clock();

This function returns a value of type long (also defined in the class as type clock_t), which is the number of milliseconds since 12:00 AM that began January 1, 1980, to the nearest 10 milliseconds.  (So you get hundredths of a second reported in milliseconds).

This function may be used like the time() function, but is more useful for measuring very short intervals of time.