我制作了一个在 Windows 32 位中运行的小终端应用程序。
此应用程序从 UDP 端口监听并将数据写入 SQLite 数据库
代码:
#include <QUdpSocket>
#include <QTextStream>
#include <QSqlDriver>
#include <QSqlDatabase>
#include <QSqlQuery>
int main()
{
int i;
QTextStream qout(stdout);
//db conn or create db
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("localhost");
db.setDatabaseName("C:\\db_test\\db.sqlite");
db.open();
//create db structure
QSqlQuery *query = new QSqlQuery(db);
query->prepare("CREATE TABLE "
"MYTABLE("
"FIELD_1 VARCHAR(100) NOT NULL, "
"FIELD_2 VARCHAR(100) NOT NULL)"
);
if(query->exec() == true){
qout << "New Database Created" << endl;
} else {
qout <<"Database Alredy Exists" << endl;
}
//start UDP listener
QUdpSocket *udpSocket = new QUdpSocket(0);
udpSocket->bind(7755, QUdpSocket::ShareAddress);
i=1;
while (udpSocket->waitForReadyRead(-1)) {
while(udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
QString Rec_Data = datagram.data();
QString Sender_Address = sender.toString();
QString InsertStr = "INSERT INTO MYTABLE VALUES (:val1, :val2)";
qout << InsertStr << " " << i << endl;
query->prepare(InsertStr);
query->bindValue(":val1", Rec_Data);
query->bindValue(":val2", Sender_Address);
if(query->exec() == true){
qout << "Data stored" << endl;
} else {
qout <<"Store Error" << endl;
}
i=i+1;
}
}
}
我需要每分钟处理大约 20,000 个查询,但当我运行 (Ctrl+R) 时,它每分钟处理大约 500 个查询。
我知道出了什么问题,但我不知道是什么。
最佳答案
将多个 INSERT 操作批处理到单个事务中。
单独执行插入操作会将吞吐量限制为每秒约 60 次插入,因为在 SQLite 执行写入后读取验证时硬盘驱动器磁盘盘片必须完全旋转。
进一步阅读
INSERT is really slow - I can only do few dozen INSERTs per second
关于c++ - QT Creator + SQLite。插入速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337548/