测试QT读写锁(QReadWriteLock )和互斥锁(QReadWriteLock )的执行效率
上代码:
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QtConcurrent>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);qSetMessagePattern("(%{time hh:mm:ss.zzz} %{threadid} %{file}:%{line}): \t%{message}");QList<int> list_report;for (int round = 0; round < 5; round++){QMutex *mtx_lock = new QMutex;QReadWriteLock *rw_lock = new QReadWriteLock;QFutureWatcher<void> *watcher = new QFutureWatcher<void>;QSemaphore semaphore;QAtomicInt times = 1000 * 1000; //1mQDateTime datatime;QElapsedTimer timer;timer.start();for (int i = 0; i < 5; i++){QFuture<void> 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()<<index<<"write:times"<<write_times;});watcher->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:"<<list_report;return a.exec();
}
测试结果 :
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的执行效率。