How to record the running information of functions in your program?

294 Views Asked by At

I recently attended a coding interview and I was asked a question which I didn't know the answer to. After searching the answer on the internet for a few day, I come here call for help.

The question is described as followed: You should propose a approach to record the running information of function in your program, for example, the times of a function called, and so on.

By the way, you are not allowed to modify these functions. Maybe you want to define a global variant in these function to record the running function, but that is not allowed.

Ok! That's all about the question I met in a coding interview.

1

There are 1 best solutions below

3
On

This is the best I could come up with using C++ macros. I don't know whether it conforms to the requirements.

A very basic version just recording the count. The macro replaces all existing calls to the function with the contents of the macro, which records the stats and calls the function. Can easily be extended to record more details. Assumes there's only one function with that name or you want one count for all of them. Requires a macro for each function.

// here's our function
void func()
{ /* some stuff */ }

// this was added
int funcCount = 0;
#define func(...) do { funcCount++; func(__VA_ARGS__); } while(0)

int main()
{
    // call the function
    func();

    // print stats
    cout << funcCount << endl;

    return 0;
}

Prints 1.

A more generic version. Requires changes to how the function is called.

// here are our functions
void someFunc()
{ /* some stuff */ }
void someOtherFunc()
{ /* some stuff */ }

// this was added
map<string, int> funcCounts;
#define call(func, ...) do { funcCounts[ #func ]++; func(##__VA_ARGS__); } while(0)

int main()
{
    // call the functions
    // needed to change these from 'someFunc();' format
    call(someFunc);
    call(someOtherFunc);
    call(someFunc);

    // print stats
    for (map<string, int>::iterator i = funcCounts.begin(); i != funcCounts.end(); i++)
      cout << i->first << " - " << i->second << endl;

    return 0;
}

Prints:

someFunc - 2
someOtherFunc - 1