int inline add(int i)//这里inline应该提前到int
{
i++;
return i; //returnning local vaeiable is not good
}
int _tmain(int argc, _TCHAR* argv[])
{
int a=2;
add(a);//在这里会展开inline function.
cout < <a < <endl;
return 0;
}
int inline add(int i)
{
i++;
return i; //returnning local vaeiable is not good
}
int _tmain(int argc, _TCHAR* argv[])
{
int a=2;
add(a);//在这里会展开inline function.
cout < <a < <endl;
return 0;
}
namespace speed
{
class testImpl
{
public:
testImpl( void ) : data( 0 ) {}
void clear( void ) { data = 0; }
void test1( void )
{
for( unsigned long long i = 0ULL; i < C; ++i )
{
++data;
}
}
inline void test2( void )
{
for( unsigned long long i = 0ULL; i < C; ++i )
{
++data;
}
}
int data;
};
class testClass
{
public:
testImpl *m_Impl;
public:
testClass( void )
{
m_Impl = new testImpl();
}
~testClass( void )
{
delete m_Impl;
}
void test1( void )
{
m_Impl->test1();
m_Impl->clear();
}
void test2( void )
{
m_Impl->test2();
m_Impl->clear();
}
void test3( void )
{
for( unsigned long long i = 0ULL; i < C; ++i )
{
++m_Impl->data;
}
m_Impl->clear();
}
};
static void test( void )
{
testClass aTest;
::timeBeginPeriod( 1 );
int t0 = ::timeGetTime();
aTest.test1();
int t1 = ::timeGetTime();
aTest.test2();
int t2 = ::timeGetTime();
aTest.test3();
int t3 = ::timeGetTime();
::timeEndPeriod( 1 );
std::printf( "time of normal/inline/expand : %d/%d/%d\r\n",t1-t0,t2-t1,t3-t2 );
std::printf( "value = %d",aTest.m_Impl->data );
}
};
在我的机器上(AMD Althon XP 2200+ 512M)得到了以下平均值(多次输出,比较趋向中间值的结果):
debug :
time of normal/inline/expand : 84/67/85
value = 0
release:
time of normal/inline/expand : 36/16/19
value = 0
--------------------next---------------------
re: 几种函数形式的速度比较
首先我假设你的test2()真的在testClass::test2()内被展开.
其伪码应该为:
void testClass::test2( void )
{
/**testImpl::test2() begin**/
{
testImpl* const __impl=m_Impl;
for( unsigned long long i = 0ULL; i < C; ++i )
{
__impl->++data;
}
}
/**testImpl::test2() end**/
m_Impl->clear();
}
而testImpl::test1()又会是什么?
因为C++规定non-virtual member function其调用成本等同一个普通函数调用, 因此testImpl::test1()所对应的C伪码应该是:
void __testImpl_test1(testImpl *const This){
for( unsigned long long i = 0ULL; i < C; ++i )
{
This->++data;
}
}