1

在我的程序中,我从文本文件中读取大量数据并将其放入 QTableWidget。最初这一切都是在 GUI 线程中完成的,然后我决定对它进行多线程处理以获得更好的性能。但相反,性能明显变慢,即慢了 8 倍!所以我决定对它进行基准测试。这是我的文件:

主文件

#include <QtGui/QApplication>
#include <QMutex>
#include <QDir>
#include <string>
#include <QDebug>
#include "mainwindow.h"

QFile *logFile = NULL;
QTextStream *logStream = NULL;
QMutex *mutex = NULL;
bool *debugMode = NULL;

void myMessageOutput(QtMsgType type, const char *msg)
 {
    if(((logFile != NULL) && (debugMode != NULL)))
    {
        mutex->lock();
         switch (type)
         {
         case QtDebugMsg:
             if(!*debugMode)
             {
                 mutex->unlock();
                 return;
             }
             *logStream << msg;
             logStream->flush();
             break;
         case QtWarningMsg:
             *logStream << "\n*** Warning ***\n";
             *logStream << msg;
             *logStream << "\n*** Warning Complete ***\n";
             logStream->flush();
             break;
         case QtCriticalMsg:
             *logStream << "\n*** Critical ***\n";
             *logStream << msg;
             *logStream << "\n*** Critical Complete ***\n";
             logStream->flush();
             break;
         case QtFatalMsg:
             *logStream << "\n*** Fatal ***\n";
             *logStream << msg;
             *logStream << "\n*** Fatal Complete ***\n";
             logStream->flush();
             abort();
         }
         mutex->unlock();
    }
 }

void CreateLogFile()
{
    QString path = "C:\\Users\\abcd\\Documents\\QT\\benchmark\\output.log";
    QFile *file = new QFile(path);
    if(file->exists())
        file->remove();
    if(!file->open(QFile::WriteOnly | QFile::Text))
    {
        qFatal("Could not create log file.");
    }

    logStream = new QTextStream(file);
    logStream->setRealNumberNotation(QTextStream::FixedNotation);
    logStream->setRealNumberPrecision(16);
    logFile = file;
}

int main(int argc, char *argv[])
{
    mutex = new QMutex();
    qInstallMsgHandler(myMessageOutput);
    debugMode = new bool;
    CreateLogFile();
    *debugMode = true;

    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    w.bench2();

    return a.exec();

}

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include "multi_thread.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void bench2();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QList>
#include <QTime>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::bench2()
{
    QTableWidget *table = new QTableWidget();
    table->setRowCount(1000);
    table->setColumnCount(1000);
    for(int i = 0; i < 1000; i++)
    {
        for(int j = 0; j < 1000; j++)
            table->setItem(i, j, new QTableWidgetItem());
    }
    Multi_Thread **multis = new Multi_Thread *[4];
    QThread **thrs = new QThread *[4];
    int from;
    int to = -1;

    QTime time;
    time.start();

    for(int i = 0; i < 4; i++)
    {
        from = to + 1;
        to = from + 250;
        if(i == 3)
            to = 999;

        multis[i] = new Multi_Thread();
        multis[i]->setTable(table, from, to);
        thrs[i] = new QThread();
        connect(thrs[i], SIGNAL(started()), multis[i], SLOT(bench2_1()));
        multis[i]->moveToThread(thrs[i]);
    }

    for(int i = 0; i < 4; i++)
    {
        if(!i)
            time.start();

        thrs[i]->start();
    }

    for(int i = 0; i < 4; i++)
    {
        thrs[i]->wait();
    }
    qDebug() << "\nbench2 1 " << time.elapsed();

    for(int i = 0; i < 4; i++)
    {
        delete multis[i];
        delete thrs[i];
    }
    delete[] multis;
    delete[] thrs;


    table->clear();
    table->setRowCount(1000);
    table->setColumnCount(1000);
    for(int i = 0; i < 1000; i++)
    {
        for(int j = 0; j < 1000; j++)
            table->setItem(i, j, new QTableWidgetItem());
    }

    time.start();

    for(int i = 0; i < 1000; i++)
    {
        for(int j = 0; j < 1000; j++)
            table->item(i, j)->setText("0");
    }
    qDebug() << "\nbench2 2 " << time.elapsed();

    table->clear();
    table->setRowCount(1000);
    table->setColumnCount(1000);
    QTableWidgetItem ***items = new QTableWidgetItem **[1000];
    for(int i = 0; i < 1000; i++)
    {
        items[i] = new QTableWidgetItem *[1000];
        for(int j = 0; j < 1000; j++)
        {
            QTableWidgetItem *item = new QTableWidgetItem();
            table->setItem(i, j, item);
            items[i][j] = item;
        }
    }

    multis = new Multi_Thread *[4];
    thrs = new QThread *[4];
    to = -1;

    for(int i = 0; i < 4; i++)
    {
        from = to + 1;
        to = from + 250;
        if(i == 3)
            to = 999;

        multis[i] = new Multi_Thread();
        multis[i]->setItems(items, from, to);
        thrs[i] = new QThread();
        connect(thrs[i], SIGNAL(started()), multis[i], SLOT(bench2_2()));
        multis[i]->moveToThread(thrs[i]);
    }
    table->blockSignals(true);
    table->setUpdatesEnabled(false);
    table->setWordWrap(false);

    for(int i = 0; i < 4; i++)
    {
        if(!i)
            time.start();

        thrs[i]->start();
    }

    for(int i = 0; i < 4; i++)
    {
        thrs[i]->wait();
    }
    qDebug() << "\nbench2 3 " << time.elapsed();
    table->blockSignals(false);
    table->setUpdatesEnabled(true);
    table->setWordWrap(true);

    for(int i = 0; i < 4; i++)
    {
        delete multis[i];
        delete thrs[i];
    }
    delete[] multis;
    delete[] thrs;

    table->clear();
    for(int i = 0; i < 1000; i++)
    {
        delete[] items[i];
    }
    delete[] items;

}

多线程.h

#ifndef MULTI_THREAD_H
#define MULTI_THREAD_H

#include <QObject>
#include <QThread>
#include <QTableWidget>

class Multi_Thread : public QObject
{
    Q_OBJECT
public:
    explicit Multi_Thread();
    void setTable(QTableWidget *tab, int f, int t);
    void setItems(QTableWidgetItem ***i, int f, int t);

private:
    QTableWidget *table;
    QTableWidgetItem ***items;
    int from;
    int to;

signals:

public slots:
    void bench2_1();
    void bench2_2();

};

#endif // MULTI_THREAD_H

多线程.cpp

#include "multi_thread.h"

Multi_Thread::Multi_Thread() : QObject()
{
}

void Multi_Thread::setTable(QTableWidget *tab, int f, int t)
{
    table = tab;
    from = f;
    to = t;
}

void Multi_Thread::setItems(QTableWidgetItem ***i, int f, int t)
{
    items = i;
    from = f;
    to = t;
}

void Multi_Thread::bench2_1()
{
    for(int i = from; i <= to; i++)
    {
        for(int j = 0; j < 1000; j++)
        {
            table->item(i, j)->setText("0");
        }
    }
    QThread::currentThread()->exit(0);
}

void Multi_Thread::bench2_2()
{
    for(int i = from; i <= to; i++)
    {
        for(int j = 0; j < 1000; j++)
        {
            items[i][j]->setText("0");
        }
    }
    QThread::currentThread()->exit(0);
}

输出日志

bench2 1  7654 
bench2 2  1160 
bench2 3  8021 

奇怪的是,我期望“bench2 3”比“bench2 1”快。

PS:我的笔记本电脑硬件可能需要 4 个线程才能达到 100% 的使用率。请根据您的硬件要求对其进行编辑。可以从环境变量中得知。

4

2 回答 2

2

table->item(...)->setText()从 GUI 线程以外的任何线程调用都是未定义的行为。不要这样做。很高兴您使用 a QObjectin aQThread来完成这项工作,但您不能直接调用存在于其他线程中的对象的方法。

内部模型将为dataChanged()您的每个更新调用视图的插槽。除了每个项目的内存分配之外,这可能是减速的原因。

在单独的线程中准备数据模型的典型方法是:

  1. 在单独的线程中实例化模型。此时模型必须尚未连接到任何视图。用数据初始化模型。它可以是一个QStandardItemModel或自定义模型。自定义模型并不难,如果您不需要为每个项目执行内存分配,通常效率会更高。

  2. 将模型连接到视图(QTableView,不是QTableWidget)。为方便起见,您可以将其移至 gui 线程,尽管您不必这样做。

  3. 只能从模型所在的线程访问模型,除非您使用排队的方法调用或排队的信号槽连接。视图使用后者,因此可以存在于与模型分开的线程中。

AQTableWidget将内部QStandardItemModelQTableView. 如果要单独处理模型,只需将模型类与视图类隔离使用即可。

于 2013-09-18T15:43:26.283 回答
2

这个答案有一种不同的策略,可以非常有效地将大量数据(时间和内存)放入 QTableView 中。我还为对同一行的连续请求缓存了一行解析的数据。

于 2013-09-18T15:34:28.140 回答