Measuring the machine time needed to execute a function. Beginner
Hi
I'm trying to measure the time needed to execute a function. I have a small corde the works, I don't know if it's correct, but it works. Here is the code:
struct timeval start1,stop1 ;
gettimeofday(&start1, NULL);
foo();
gettimeofday(&stop1, NULL);
printf("Time= %lu\n", );
stop1.tv_usec-start1.tv_usec
Now I want to know the average time needed to exacute that function, so I extend my code:
struct timeval start1,stop1 ;
int k ;
int time_total1;
time_total1 = 0;
int n_times = 1e5;
for (k = 0; k < n_times ; k++){
gettimeofday(&start1, NULL);
foo();
gettimeofday(&stop1, NULL);
time_total1 += (stop1.tv_usec-start1.tv_usec );
}
printf("Average ime= %f\n", (float)time_total1/(float)n_times);
The code works but not always, sometimes "time_total1" variable has negative value. I suppose it's something related to the memory allocations and types, but I can't figure where the problem is. I'm completely beginner.
Thanks in advance
Posted Aug 25, 2017, 11:37 AM UTC
210