the results can depend on the compiler and level of optimization used.
this is a similar program (which uses functions from <time.h> to measure time)
-
#include <iostream.h>
-
#include <time.h>
-
#include <stdlib.h>
-
-
-
clock_t clock_start; /* holds clock start time */
-
-
// start clock
-
void timer_start() { clock_start = clock(); }
-
-
// return elapsed time on clock ticks
-
clock_t timer() { return((clock() - clock_start) ) ; }
-
-
class TestClass
-
{
-
public:
-
int variable;
-
int ReturnVariable(int x); //Only the declaration.
-
inline int ReturnVariableInline(int x)
-
{return variable*x;}; //inline.
-
-
TestClass();
-
~TestClass();
-
};
-
-
int TestClass::ReturnVariable(int x)
-
{
-
return variable*x;
-
}
-
-
TestClass::TestClass()
-
{
-
variable = 5;
-
}
-
-
TestClass::~TestClass() {}
-
-
int main()
-
{
-
TestClass test;
-
int z=1;
-
long begin, end, i;
-
-
timer_start();
-
long int a = 0;
-
timer_start();
-
for(i = 0; i < 1000000000L ; i++)
-
{
-
a += test.ReturnVariable(z);
-
}
-
cout << "result " << a << " Returning by a function : time :" << timer() << endl;
-
-
a=0;
-
timer_start();
-
for(i = 0; i < 1000000000L ; i++)
-
{
-
a += test.ReturnVariableInline(z);
-
}
-
cout << "result " << a << " Returning by an inline function : time :" << timer()<< endl;
-
-
a=0;
-
timer_start();
-
for(i = 0; i < 1000000000L ; i++)
-
{
-
a += test.variable*z;
-
}
-
cout << "result " << a << " Simply reading the value : time :" << timer() << endl;
-
system("pause");
-
return 0;
-
}
-
with g++ no optimization
result 705032704 Returning by a function : time :10641
result 705032704 Returning by an inline function : time :10281
result 705032704 Simply reading the value : time :5031
with g++ optimization -O3
result 705032704 Returning by a function : time :875
result 705032704 Returning by an inline function : time :860
result 705032704 Simply reading the value : time :875
with Turbo C V3.0 small memory model
result 705032704 Returning by a function : time :515
result 705032704 Returning by an inline function : time :330
result 705032704 Simply reading the value : time :330
with Turbo C V3.0 huge memory model
result 705032704 Returning by a function : time :2359
result 705032704 Returning by an inline function : time :337
result 705032704 Simply reading the value : time :338