Thursday, November 20, 2008

Time elapsed between two function calls using program in C programming language ?

How do I get the time elapsed between two function calls ?

Ans: The function difftime( ) finds the difference between two times. It calculates the elapsed time in seconds and returns the difference between two times as a double value.
#include 
#include 
#include 
main( )
{
int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ;
int s ;
time_t t1, t2 ; // time_t defines the value used for time function
s = sizeof ( a ) / 2 ;
t1 = time ( NULL ) ;
sel_sort ( a, s ) ; // sort array by selection sort
bub_sort ( a, s ) ; // sort array by bubble sort method
t2 = time ( NULL ) ;
printf ( "\nThe difference between two function calls is %f", difftime (
t2, t1 ) ) ;
}
In the above program we have called difftime( ) function that returns the time elapsed from t1 to t2.
88. General
main( )
{
char *s ;
s = fun ( 128, 2 ) ;
printf ( "\n%s", s ) ;
}
fun ( unsigned int num, int base )
{
static char buff[33] ;
char *ptr ;
ptr = &buff [ sizeof ( buff ) - 1 ] ;
*ptr = '\0' ;
do
{
*--ptr = "0123456789abcdef"[ num % base ] ;
num /= base ;
} while ( num != 0 ) ;
return ptr ;
}
The above program would convert the number 128 to the base 2. You can convert a number to a hexadecimal or octal form by passing the number and the base, to the function fun( ).

No comments:

Blog List