Last active
October 21, 2020 18:21
-
-
Save PatrickRudgeri/aacebff208e46eb16e966b5186ee3629 to your computer and use it in GitHub Desktop.
A simple example of a function wrapper in c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include <cmath> | |
using namespace std; | |
using namespace std::chrono; | |
string func1(const string &nome) { | |
int someVar = 1; | |
for (int i = 0; i < 1e7; i++) { | |
someVar *= i * i; | |
} | |
return nome + "_func1"; | |
} | |
float func2(int step) { | |
float someAccum = 0.0; | |
int size = 1e7; | |
for (int i = 0; i < size; i++) { | |
someAccum += pow(step, 2); | |
} | |
return someAccum / (float) size; | |
} | |
template<typename returnType, typename paramType> | |
returnType timeWrapper(paramType param, returnType func(paramType), int n = 100) { | |
double meanTime, stdTime, timeVec[n], timeAccum=0.0; | |
high_resolution_clock::time_point begin, end; | |
returnType returnVar; | |
for (int i = 0; i < n; i++) { | |
begin = high_resolution_clock::now(); | |
returnVar = func(param); | |
end = high_resolution_clock::now(); | |
timeVec[i] = duration_cast<duration<double>>(end - begin).count(); | |
timeAccum += timeVec[i]; | |
} | |
// calc mean | |
meanTime = timeAccum / n; | |
// calc std | |
for (int i = 0; i < n; i++) { | |
stdTime = pow(timeVec[i] - meanTime, 2) / n; | |
} | |
stdTime = pow(stdTime, 0.5); | |
cout << " | " << "time: " << meanTime << " +- " << stdTime << " sec" << endl; | |
cout << "\treturn: " << returnVar << endl; | |
return returnVar; | |
} | |
int main() { | |
//execute 100 times func1 and measure time | |
cout << "func1 (n=100)| "; | |
timeWrapper<string, const string &>("Patrick_Rudgeri", func1); | |
//execute 100 times func1 and measure time | |
cout << "func2 (n=100)| "; | |
timeWrapper<float, int>(15, func2); | |
//execute 300 times func1 and measure time | |
cout << "func2 (n=300)| "; | |
timeWrapper<float, int>(15, func2, 300); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment