Wednesday, 21 August 2013

Function call takes longer in composite class

Function call takes longer in composite class

Trying to understand run time performance with class composition, I wrote
the following test code. In it, I compare the time taken to call a
function directly as a member function of a class, versus to call it
through a composite class that has the original class as a member.
It seems like the methods should take comparable time, but they don't:
calling through the composite class takes almost twice as long.
Here's the code:
const int REPS(1e8);
const double INPUT(5.29);
class Base {
public:
inline double BaseFunc(double x) const;
};
double Base::BaseFunc(double x) const {
return 2.718*x + 3.14;
};
class Super {
public:
inline double BaseFunc(double x) const;
private:
Base b_;
};
double Super::BaseFunc(double x) const {
b_.BaseFunc(x);
};
int main() {
auto t0 = std::chrono::high_resolution_clock::now();
// Call to base directly.
Base b;
for (int i = 0; i < REPS; ++i)
b.BaseFunc(INPUT);
auto t1 = std::chrono::high_resolution_clock::now();
// Call to base through composited class.
Super s;
for (int i = 0; i < REPS; ++i)
s.BaseFunc(INPUT);
auto t2 = std::chrono::high_resolution_clock::now();
// Find average durations.
auto diff1 =
std::chrono::duration_cast<std::chrono::nanoseconds>(t1-t0).count();
diff1 /= REPS;
auto diff2 =
std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count();
diff2 /= REPS;
std::cout << "Calling directly to base took " << diff1 << "nsec.\n";
std::cout << "Calling to base through a composited class took " << diff2
<< "nsec.\n";
}
Compiling with g++ Version 4.7.2, with -std=c++11 -O0 -Winline, I get:
Calling directly to base took 13nsec.
Calling to base through a composited class took 24nsec.
Why is there such a disparity between these two ways of calling
essentially the same function? I figure that since everything is inlined
(gcc doesn't tell me otherwise) these should be the same thing.
Am I thinking about this totally incorrectly? Any help is appreciated!
Thanks!

No comments:

Post a Comment