Explication
Hello, I want to create a function that can execute any type of function, indicating at the end of its execution the time it took. The called function can have a return value or not and 0 or more parameters of any type.
The calling function must print something like this:
Running "myFunction" .....
Done ! (5210ms)
Basically I want to create a function that calls any type of function passed as a parameter by adding code before and after the call.
What I have done
For now I do it like this.
The calling function:
template <typename T>
T callFunctionPrintTime(std::string fnName, std::function<T()> fn) {
std::cout << ">> Running " << fnName << " ... " << std::endl;
auto t1 = std::chrono::high_resolution_clock::now();
//Call to the target function
T retVal = fn();
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
std::cout << "Done ! (" << duration << " ms)" << std::endl;
return retVal;
}
The main
int main()
{
//Store the function to call
std::function<unsigned long()> fn = []() {
return myFunction(15, 10000);
};
//Use of the function we are interested in
auto i = callFunctionPrintTime("myFunction", fn);
//The return value of myFunction can be used in the rest of the program.
std::cout << "i: " << i << std::endl;
}
myFunction
This function doesn't matter, it can be anything.
Here we execute a while loop for a given maximum time or maximum number of loop and retrieve the number of loop performed.
unsigned long myFunction(long maxMs, unsigned long maxI) {
unsigned long i = 0;
auto tStart = std::chrono::high_resolution_clock::now();
while (maxMs > (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - tStart).count()) &&
maxI > i) {
i++;
}
return i;
}
Question
What is the best way for you to do this? I am not satisfied with my code.
I'm not sure I'm using the right way to pass a function of any kind by parameter.
Moreover by using a lambda expression to store my function I can't retrieve the name of the called function. So I have to pass its name by parameter.