Get CPU Time Used
From CodeCodex
The times(2) system call returns the total amount of user and system CPU time used by the current process and its children. Often you want to determine the amount of CPU time used by a particular section of code; the following routines let you do this.
typedef struct
{
double User;
double UserChildren;
double System;
double SystemChildren;
double Elapsed; /* since some arbitary, but consistent, point in the past */
} TimesUsed; /* all in seconds */
void GetTimesUsed
(
TimesUsed & Times
)
/* returns total CPU & elapsed times in seconds. */
{
struct tms TicksUsed;
const long TicksPerSecond = sysconf(_SC_CLK_TCK);
Times.Elapsed = (double)times(&TicksUsed) / TicksPerSecond;
Times.User = (double)TicksUsed.tms_utime / TicksPerSecond;
Times.UserChildren = (double)TicksUsed.tms_cutime / TicksPerSecond;
Times.System = (double)TicksUsed.tms_stime / TicksPerSecond;
Times.SystemChildren = (double)TicksUsed.tms_cstime / TicksPerSecond;
} /*GetTimesUsed*/
void GetTimesUsed
(
TimesUsed & Times,
TimesUsed & PreviousTimes
)
/* returns CPU & elapsed times since PreviousTimes in seconds.
PreviousTimes is updated to total times used so far, so next
call with same PreviousTimes arg will return times used since
this call. */
{
TimesUsed NewTimes;
GetTimesUsed(NewTimes);
Times.User = NewTimes.User - PreviousTimes.User;
Times.UserChildren = NewTimes.UserChildren - PreviousTimes.UserChildren;
Times.System = NewTimes.System - PreviousTimes.System;
Times.SystemChildren = NewTimes.SystemChildren - PreviousTimes.SystemChildren;
Times.Elapsed = NewTimes.Elapsed - PreviousTimes.Elapsed;
PreviousTimes = NewTimes;
} /*GetTimesUsed*/
To use these routines, declare two TimesUsed structs: one will hold the time used prior to the section you want to time, and the second one will be filled in with the amount of time actually used over that section. E.g.
TimesUsed Before, After;
GetTimesUsed(Before);
/* ... section of code you want to time ... */
GetTimesUsed(After, Before);
cout
<< "Time taken: user "
<< After.User;
if (After.UserChildren != 0.0)
{
cout
<< "+"
<< After.UserChildren;
} /*if*/
cout
<< ", system "
<< After.System;
if (After.SystemChildren != 0.0)
{
cout
<< "+"
<< After.SystemChildren;
} /*if*/
cout
<< ", elapsed "
<< After.Elapsed
<< "\n";
Note that the Before struct gets updated with the total process elapsed times on the second call; this makes it easy to get timings for a whole sequence of code sections in succession, e.g.
TimesUsed SoFar, InSection1, InSection2; GetTimesUsed(SoFar); /* ... first section of code you want to time ... */ GetTimesUsed(InSection1, SoFar); /* ... second section of code you want to time ... */ GetTimesUsed(InSection2, SoFar);

