问题
I have been reading about this theme. I have readed a lot of possible solutions, so please, dont mark my question as duplicated, only need a puntual solution of this problem.
I have a function which calculate time of execution of some code. This code will be sent as argument (will be a function).
This is the function which calculate the time:
double executionTime( /* HERE I WANNA PASS THE FUNCTION TO CALCULATE EXECTIME*/ )
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
// HERE GOES CODE TO PROCCESS
QueryPerformanceCounter(&end);
interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;
return (interval);
}
I have tryed this (and another ways, but it is the most visible):
double executionTime( void (*f)() )
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
// Function to proccess
f();
QueryPerformanceCounter(&end);
interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;
return (interval);
}
I do not know if arguments of function to proccess are important. In some sites said yes, in another said no. The declaration of the function that I wanna proccess is:
int readFileAndInsertRegs(char *nombreFichero, PERSONA *tablaHash[], int tam, int tipoInsertado, int tipoPruebaColision)
I have called function executionTime
like:
executionTime( readFileAndInsertRegs("./files/listaActores.csv", &tablaHash, TAM_E1, NORMAL, LINEAL) );
Can anyone help me with this particular problem?
Thank you.
回答1:
usually the way to do so is to pass function arguments to the executionTime
and call the function with them, i.e.
double executionTime( void (*f)(), char *arg1, PERSONE arg2[], ... )
{
// do preamble
f(arg1, arg2, .....);
// finish
}
...
executionTime( &readFileAndInsertRegs, "./files/listaActores.csv", &tablaHash, TAM_E1, NORMAL, LINEAL));
here is a working example:
#include <stdio.h>
void process1(void (*f)(), int farg) {
f(farg);
}
void f1(int arg) {
printf("f1: %d\n", arg);
}
int main() {
process1(&f1, 10);
return 0;
}
and, in 'c' you do not need to declare all arguments of the function, though you can, and it is a good idea to do so. Compiler could do an additional checking then
void process1(void (*f)(int), int farg) {
来源:https://stackoverflow.com/questions/52788554/passing-a-function-as-argument-to-other-function