I wrote a function template to measure time:
#include <ctime>
template <typename FUNCTION,typename INPUT,int N>
double measureTime(FUNCTION f,INPUT inp){
// double x;
double duration = 0;
clock_t begin = clock();
for (int i=0;i<N;i++){
// x = f(inp);
f(inp);
}
clock_t end = clock();
// std::cout << x << std::endl;
return double(end-begin) / CLOCKS_PER_SEC;
}
And I use it like this:
#include <iostream>
typedef std::vector<double> DVect;
double passValue(DVect a){
double sum = 0;
for (int i=0;i<a.size();i++){sum += sum+a[i];}
return sum;
}
typedef double (*passValue_type)(DVect);
int main(int argc, char *argv[]) {
const int N = 1000;
const int size = 10000;
std::vector<double> v(size,0);
std::cout << measureTime<passValue_type,DVect,N>(passValue,v) << std::endl;
}
The aim is to reliably measure the cpu time of different functions, e.g. pass-by-value vs pass-by-reference. Actually it seems to work nicely, however, sometimes the resulting time is too short to be measured and i just get 0 as result. To make sure the function is called, I printed the result of the call (see comments in above code). This I would like to avoid and I would like to keep the template as simple as possible, so my question is:
How can I make sure that the function is really called and not optimised away (because the return value is not used)?