Linux で boost::atomic と pthread ミューテックスのパフォーマンスを比較しようとしています。
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ;
int g = 0 ;
void f()
{
pthread_mutex_lock(&mutex);
++g;
pthread_mutex_unlock(&mutex);
return ;
}
const int threadnum = 100;
int main()
{
boost::threadpool::fifo_pool tp(threadnum);
for (int j = 0 ; j < 100 ; ++j)
{
for (int i = 0 ; i < threadnum ; ++i)
tp.schedule(boost::bind(f));
tp.wait();
}
std::cout << g << std::endl ;
return 0 ;
}
時間です:
real 0m0.308s
user 0m0.176s
sys 0m0.324s
boost::atomic: も試しました
boost::atomic<int> g(0) ;
void f()
{
++g;
return ;
}
const int threadnum = 100;
int main()
{
boost::threadpool::fifo_pool tp(threadnum);
for (int j = 0 ; j < 100 ; ++j)
{
for (int i = 0 ; i < threadnum ; ++i)
tp.schedule(boost::bind(f));
tp.wait() ;
}
std::cout << g << std::endl ;
return 0 ;
}
時間です:
real 0m0.344s
user 0m0.250s
sys 0m0.344s
何度も実行しましたが、タイミングの結果は似ています。
アトミックは、ミューテックス/セマフォによって引き起こされるシステムコールのオーバーヘッドを回避するのに本当に役立ちますか?
どんな助けでも大歓迎です。
ありがとう
UPDATE : ループ数を 1000000 に増やします
for (int i = 0 ; i < 1000000 ; ++i)
{
pthread_mutex_lock(&mutex);
++g;
pthread_mutex_unlock(&mutex);
}
boost::atomic に似ています。
「time ./app」で時間をテストする
ブーストを使用:アトミック:
real 0m13.577s
user 1m47.606s
sys 0m0.041s
pthread ミューテックスを使用します。
real 0m17.478s
user 0m8.623s
sys 2m10.632s
pthread が sys 呼び出しにより多くの時間を使用するため、boost:atomic の方が高速であるようです。
user time + sys が real time よりも大きいのはなぜですか?
どんなコメントでも大歓迎です!