简体   繁体   中英

Passing a function as argument to other function

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.

usually the way to do so is to pass function arguments to the executionTime and call the function with them, ie

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM