NOTES The C standard allows for arbitrary values at the start of the program; subtract the value returned from a call to clock() at the start of the program to get maximum portability.
Note that the time can wrap around. On a 32bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.
On several other implementations, the value returned by clock() also includes the times of any children whose status has been collected via wait()(or another wait-type call). Linux does notinclude the times of waited-for children in the value returned by clock(). The times() function, which explicitly returns (separate) information about the caller and its children, may be preferable.
[armlinux@lqm src]$ cat cal_time.c /* * Copyright 2007 (c), Shandong University * All rights reserved. * * Filename : cal_time.c * Description: calculate the time of program which carries out. * Author : Liu Qingmin * Version : 1.0 * Date : 2007-10-15 */
/* * Function : cal_time * Description: calculate the time of program which executes * Parameters : p_func p_func_arr[] -- the function collection to be tested * int size -- the number of functions to be tested * Return : none * Notice : you cannot calculate the number of element in array which is * passed by value. */ void cal_time(p_func p_func_arr[],int size) { structtimeval start, end; unsignedint sum = 0; int i;
for(i=0; i<size; i++){ /* get start time */ gettimeofday(&start,NULL);
/* Test Code */ p_func_arr[i]();
/* get end time */ gettimeofday(&end,NULL);
sum +=(1000000 *(end.tv_sec - start.tv_sec) +(end.tv_usec - start.tv_usec)); }
/* print the result */ printf("time: %.6f s./n",(double)sum / 1000000); }
main.c
[armlinux@lqm src]$ cat main.c /* * Copyright 2007 (c), Shandong University * All rights reserved. * * Filename : main.c * Description: * Author : Liu Qingmin * Version : 1.0 * Date : 2007-10-15 */
#include<stdio.h> #include<cal_time.h>
/* macro to calculate the number of array */ #define ARRAY_SIZE(x)(sizeof(x)/sizeof((x)[0]))
/* test function */ int test1(void); int test2(void);
p_func p_func_arr[]={ &test1, &test2 };
int main(void) { cal_time(p_func_arr, ARRAY_SIZE(p_func_arr));