测试QT读写锁(QReadWriteLock )和互斥锁(QReadWriteLock )的执行效率

上代码:

#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qSetMessagePattern("(%{time hh:mm:ss.zzz} %{threadid} %{file}:%{line}): \t%{message}");

    QList list_report;

    for (int round = 0; round < 5; round++)
    {
        QMutex *mtx_lock = new QMutex;
        QReadWriteLock *rw_lock = new QReadWriteLock;
        QFutureWatcher *watcher = new QFutureWatcher;
        QSemaphore semaphore;

        QAtomicInt times = 1000 * 1000; //1m
        QDateTime datatime;

        QElapsedTimer timer;
        timer.start();

        for (int i = 0; i < 5; i++)
        {
            QFuture future = QtConcurrent::run([&, i]() {
                int index = i;
                int write_times{0};

                semaphore.release(1);

                while (times > 0) {
                    int type = QRandomGenerator::global()->bounded(2);
                    if (type == 1 and index == 0) {
//                        QWriteLocker locker(rw_lock);
//                        datatime = QDateTime::currentDateTime();

                        QMutexLocker locker(mtx_lock);
                        datatime = QDateTime::currentDateTime();

                        write_times++;

                    } else {
//                        QReadLocker locker(rw_lock);
//                        auto newdata = datatime;

                        QMutexLocker locker(mtx_lock);
                        auto newdata = datatime;


                    }
                    times--;
                }

                qDebug()<setFuture(future);
        }

        semaphore.acquire(1);
        watcher->waitForFinished();
        qDebug() << round << "QFuture (ms)" << timer.elapsed()<<"------------------------------------";

        list_report.append(timer.elapsed());

        delete (watcher);
        delete (rw_lock);
        delete (mtx_lock);
    }

    qDebug()<<"report:"<

测试结果 :

5线程 (1000  * 1000)
写概率 指定线程写 结果(单位:ms) 平均写入次数
读写锁 1/1000 (193, 191, 183, 188, 186) 200
互斥锁 1/1000 (111, 112, 109, 105, 106) 200
互斥锁 1/2 (2808, 2790, 2722, 2719, 2800) 100000
互斥锁 1/5 (1160, 1133, 1142, 1163, 1137) 40000
读写锁 1/5 (4627, 4689, 4614, 4524, 4617) 40000
互斥锁 1/2 (321, 303, 399, 358, 338) 50000
读写锁 1/2 (1406, 1387, 1412, 1388, 1412) 50000

小结:

读写锁QReadWriteLock 在指定线程写多个线程读,效率明显比多个线程同时读写好。

但是,都远低于互斥锁QMutex的执行效率。

你可能感兴趣的:(qt,c++,线程锁)