zhangJW_cn 阅读(788) 评论(0)
详细见代码,不过发现windows 7上和windows xp上部分调用性能差异巨大。

#include
#include

#define NUM 80000000

class lockable
{
public:
lockable( void )
{
::InitializeCriticalSection( &m_cs );
}
~lockable( void )
{
::DeleteCriticalSection( &m_cs );
}

void lock( void ) const
{
::EnterCriticalSection( &m_cs );
}
bool tryLock( void ) const
{
return ::TryEnterCriticalSection( &m_cs ) != 0;
}
void unlock( void ) const
{
::LeaveCriticalSection( &m_cs );
}

private:
lockable( const lockable &rhs );
lockable &operator = ( const lockable &rhs );

mutable CRITICAL_SECTION m_cs;
};

int main( int argc,char *argv[] )
{
lockable lock;
LARGE_INTEGER yo = {};
int hold1 = 1317, hold2 = 1317;
int tmp1 = 0, tmp2 = 0, tmp3 = 0, tmp4 = 0;
const DWORD t1 = GetTickCount();
for( int i = 0; i < NUM; ++i )
{
tmp1 += GetCurrentThreadId();
}
const DWORD t2 = GetTickCount();
for( int i = 0; i < NUM; ++i )
{
tmp2 += ( hold1 = hold1 * 214013L + 2531011L );
}
const DWORD t3 = GetTickCount();
for( int i = 0; i < NUM; ++i )
{
QueryPerformanceCounter( &yo );
tmp3 += yo.u.LowPart;
}
const DWORD t4 = GetTickCount();
for( int i = 0; i < NUM; ++i )
{
lock.lock();
tmp4 += ( hold2 = hold2 * 214013L + 2531011L );
lock.unlock();
}
const DWORD t5 = GetTickCount();

std::cout
<< "time1 = " << t2 - t1
<< " time2 = " << t3 - t2
<< " time3 = " << t4 - t3
<< " time4 = " << t5 - t4
<< " tmp1 = " << tmp1 << " tmp2 = " << tmp2
<< " tmp3 = " << tmp3 << " tmp4 = " << tmp4 << std::endl;

system( "pause" );

return 0;
}

之前有一次lock的测试,这里的简单运算采用的是rand()调用,可能是因为有TLS的原因,当时的lock成本表现接近为0。

下面是部分参考数据(不是同一台电脑):
windows 2003运行数据参考:time1 = 407 time2 = 672 time3 = 17546 time4 = 4782
windows 7运行性能数据参考:time1 = 421 time2 = 483 time3 = 1139 time4 = 2169

发表评论
切换编辑模式