C++加線程鎖相比不加線程鎖的性能到底損耗了多少


測試結果

我們日常多線程編程一定用到鎖,那是不是鎖不沖突就不耗時了呢?
如果鎖耗時,那么具體會讓性能減多少呢?

經過測試,結果如下:
運行10s如下:
不加鎖:303637450
加鎖:171365749
比值:1.8
也就是說不加鎖比加鎖快了近1倍。

PS:
本人的CPU型號是:CPU型號:Intel(R) Xeon(R) CPU E5-2630 0 @ 2.30GHz
因為每個循環都取時間,所以測試結果本身並不能代表CPU的性能。
雖然加鎖會損耗性能,但是也不見得比你“存多分數據,頻繁同步”會慢。

測試程序代碼

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/timeb.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

#include <iostream>

using namespace std;

typedef long long Int64;

static pthread_mutexattr_t  sMutexAttr;
static pthread_once_t sMutexAttrInit = PTHREAD_ONCE_INIT;
void MutexAttrInit()
{
    memset(&sMutexAttr, 0, sizeof(pthread_mutexattr_t));
    pthread_mutexattr_init(&sMutexAttr);
}

class OSMutex
{
public:
    OSMutex(){
        (void)pthread_once(&sMutexAttrInit, MutexAttrInit);
        (void)pthread_mutex_init(&fMutex, &sMutexAttr);
        m_lockingthread = 0;
        m_lockingtimes = 0;
    }
    ~OSMutex(){
        pthread_mutex_destroy(&fMutex);
    }
    void Lock(){
	(void)pthread_mutex_lock(&fMutex);
    }
    void Unlock() {
	pthread_mutex_unlock(&fMutex);
    }
    bool TryLock(){
	int theErr = pthread_mutex_trylock(&fMutex);
	if (theErr != 0)
	{
            return false;
	}
    }
private:
    pthread_mutex_t fMutex;
    pthread_t	    m_lockingthread;
    int		    m_lockingtimes;
};

Int64 milliseconds()
{
    struct timeval t;
    struct timezone tz;
    int theErr = ::gettimeofday(&t, &tz);
    if(theErr < 0)
    {
	printf("gettimeofday failed\n");
    }

    Int64 tmp = (Int64)t.tv_sec * 1000 + t.tv_usec / 1000;
    static Int64 last = 0x7FFFFFFFFFFFFFFFLL;
	static int count = 0;
	if((tmp - last)/10000 != 439)	
	{
		last = tmp;
		if(count != 0)
		{
			count = 0;
		}
	}
	else
	{
		count++;
		if(count > 10)
		{
			return last;
		}
		tmp = milliseconds();
	}
	
    return tmp;
}

int main()
{
    Int64 before = milliseconds();
    OSMutex mtx;
    Int64 cnt = 0;
    while (1) {
        Int64 now = milliseconds();
        if (now - before > 10000) {
            break;
        }
        //mtx.Lock();
        //mtx.Unlock();
        cnt ++;
    }
    cout << cnt << endl;
    return 0;
}

執行結果

[root@lh test]# g++ main26.cpp -o main26 -lpthread
[root@lh test]# ./main26 
303460399
[root@lh test]# ./main26 
303676424
[root@lh test]# ./main26 
303775529
[root@lh test]# vim main26.cpp 
#### 去掉Lock和Unlock的注釋重新編譯
[root@lh test]# g++ main26.cpp -o main26 -lpthread
[root@lh test]# ./main26 
172484106
[root@lh test]# ./main26 
168165401
[root@lh test]# ./main26 
173447741


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM