I'm trying to write a code that evaluates the run-time of the search algorithm, and I have doubts how to do it correctly. I want to pass a function linear_search to the function code_timer, and code_timer function is expected to evaluate the execution time of the linear search function. In order to solve this problem, I'm trying to use a pointer to a function.
// Search Algorithm function prototype
int *linear_search(int arr[], int arr_size, int val);
// Code timing function that evaluates the performance of the algorithm function
double code_timer( int *arr, int arr_size, int val, int nrun,
int* (*search_algorithm)(int *arr, int arr_size, int val) )
{
double interval = 0;
clock_t start, end;
int *ptr = NULL;
start = clock();
/* Code under Test */
for (int j = 0; j < nrun; j++) {
ptr = (*search_algorithm)(arr, arr_size, val);
}
/* End of Code under Test */
end = clock();
interval = (double)(end - start) / (double)(nrun) / (double) CLOCKS_PER_SEC * 1000000.0;
return interval; // in microseconds (mcs)
}
Finally I need to call the function code_timer with the function linear_search as an argument.
#define SIZE 100000 //size of data array
#define NRUN 100 // number of runs
int main(void) {
...
// calling code_timer with a function linear_search as a parameter
linear_result = code_timer(benchmark_data, SIZE, check_point, NRUN, linear_search);
}
I would like to know if I'm doing it correctly, and if no, please advise the way I could do it. Thank you!
Update: My main concern is pointer to function:
- Am I declaring it correctly as an argument?
double code_timer( int *arr, int arr_size, int val, int nrun,
int* (*search_algorithm)(int *arr, int arr_size, int val) );
- Am I dereferencing it correctly in code_timer and main functions?
// this is from code_timer function
for (int j = 0; j < nrun; j++) {
ptr = (*search_algorithm)(arr, arr_size, val);
}
// this is from main function
linear_result = code_timer(benchmark_data, SIZE, check_point, NRUN, linear_search);