#include <chrono>
#include <iostream>
double perform_computation(int);
void benchmark()
{
using namespace std;
auto start = chrono::high_resolution_clock::now();
double answer = perform_computation(42);
auto delta = chrono::high_resolution_clock::now() - start;
cout << "The answer is: " << answer << ". The computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms";
}
The above example has some problems, because the compiler is allowed to:
#include <chrono>
#include <iostream>
double perform_computation(int);
void benchmark()
{
using namespace std;
// reorder: place perform_computation here
auto start = chrono::high_resolution_clock::now();
double answer = perform_computation(42); // perform constant-folding
auto delta = chrono::high_resolution_clock::now() - start;
// or reorder: place perform_computation here
cout << "The answer is: " << answer << ". The computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms";
}
The paper proposes to add two new functions to the standard library:
#include <chrono>
#include <iostream>
#include <benchmark>
double perform_computation(int);
void benchmark()
{
using namespace std;
auto start = chrono::high_resolution_clock::now();
int value = 42;
experimental::benchmark::touch(value);
double answer = perform_computation(value);
experimental::benchmark::keep(answer);
auto delta = chrono::high_resolution_clock::now() - start;
cout << "The answer is: " << answer << ". The computation took "
<< chrono::duration_cast<chrono::milliseconds>(delta).count()
<< " ms";
}
Some benchmarking libraries already have keep-like functions:
Folly also provides a function similar to touch:
A prototype implementation exists in two flavors:
Compiler intrinsics are required for proper implementation of this feature.