Operating System - HP-UX
1819681 Members
3665 Online
109605 Solutions
New Discussion

How to Calculate Execution time in C/C++?

 

How to Calculate Execution time in C/C++?

Is there some way of calculating the execution time in C/C+++?I have gone through some code on the internet using assembly programming.Is there some way that we can calculate CPU time taken and memory usage without using assembly in C/C++?
1 REPLY 1
H.Merijn Brand (procura
Honored Contributor

Re: How to Calculate Execution time in C/C++?

'man times' or http://www.qnx.com/developer/docs/qnx_6.1_docs/neutrino/lib_ref/t/times.html (one of many, but this is the first hit I got from google with times+execution+process+libc)

times()
Get time-accounting information
Synopsis:

#include
clock_t times( struct tms* buffer );
Library:
libc
Description:
The times() function stores time-accounting information in the structure pointed to by buffer. The type clock_t and the tms structure are defined in the header file.
The tms structure contains at least the following members:
clock_t tms_utime
The member tms_utime is the CPU time charged for the execution of user instruction.
clock_t tms_stime
The member tms_stime is the CPU time charged for execution by the system on behalf of the process.
clock_t tms_cutime
The member tms_cutime is the sum of the tms_utime for this process, and the tms_cutime values of the child processes.
clock_t tms_cstime
The value tms_cstime is the sum of the tms_stime and the tms_cstime values of the child processes.

All times are in CLK_TCK'ths of a second. CLK_TCK is defined in the header file. A CLK_TCK is the equivalent of:

#define sysconf( _SC_CLK_TCK )
The times of a terminated child process are included in the tms_cutime and tms_cstime elements of the parent when a wait() or waitpid() function returns the process ID of this terminated child. If a child process hasn't waited for its terminated children, their times aren't included in its times.
Returns:
The elapsed real time, in CLK_TCK'ths of a second, since the process was started. The value returned may overflow the possible range of type clock_t.
Examples:

/*
* The following program executes the program
* specified by argv[1]. After the child program
* is finished, the cpu statistics of the child are
* printed.
*/
#include
#include
#include
#include
int main( int argc, char **argv )
{
struct tms childtim;
system( argv[1] );
times( &childtim );
printf( "system time = %d\n", childtim.tms_cstime );
printf( "user time = %d\n", childtim.tms_cutime );
return EXIT_SUCCESS;
}
Classification:
POSIX 1003.1
Safety:

Cancellation point
No
Interrupt handler
No
Signal handler
Yes
Thread
Yes

See also:
clock_gettime()

Enjoy, have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn