10亿次QLst的at与[]的运行速度的比较。
环境
- windows10系统
- Qt4.8.7(gcc 4.9.2)
- Qt5.12.3(gcc 7.3.0)
- Qt Debug构建
- 10亿次操作比较
对比
- 单位ms
- 源码最后附录
Qt版本 | 参考 | at | const at | [] | const [] |
---|---|---|---|---|---|
4.8.7 | 14 | 278 | 279 | 639 | 629 |
5.12.3 | 14 | 325 | 322 | 418 | 411 |
分析
- Qt5.12.3整体运行速度快于Qt4.8.7;
- 无论是Qt4.8.7或是Qt5.12.3的运行速度at都优于[];
- 在Qt4.8.7版本下at和[]运行速度相差不大;
- 在Qt5.12.3版本下at和[]运行速度相差不大。
附录
- Qt4.8.7与Qt5.12.3的相同QList源码
template <typename T>
inline const T &QList<T>::at(int i) const
{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::at", "index out of range");
return reinterpret_cast<Node *>(p.at(i))->t(); }
template <typename T>
inline const T &QList<T>::operator[](int i) const
{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range");
return reinterpret_cast<Node *>(p.at(i))->t(); }
template <typename T>
inline T &QList<T>::operator[](int i)
{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range");
detach(); return reinterpret_cast<Node *>(p.at(i))->t(); }
- 测试源码
#include <QList>
#include <QElapsedTimer>
#include <QUuid>
#include <QDebug>
#define ForLoop for (unsigned int i = 0; i < 10*1000*1000; i )
static QList<int> list;
static QElapsedTimer timer;
qint64 runningTime()
{
timer.start();
ForLoop {
int count = 1 2 3;
}
return timer.elapsed();
}
qint64 atRunningTime()
{
timer.start();
ForLoop {
int count = list.at(0) list.at(1) list.at(2);
}
return timer.elapsed();
}
qint64 constAtRunningTime()
{
timer.start();
ForLoop {
const int count = list.at(0) list.at(1) list.at(2);
}
return timer.elapsed();
}
qint64 squareOperationRunningTime()
{
timer.start();
ForLoop {
int count = list[0] list[1] list[2];
}
return timer.elapsed();
}
qint64 constSquareOperationRunningTime()
{
timer.start();
ForLoop {
const int count = list[0] list[1] list[2];
}
return timer.elapsed();
}
int main(int argc, char *argv[])
{
list<<0<<1<<2;
qDebug()<<"SourceRunningTime: "<<runningTime()<<"milliseconds.";
qDebug()<<"atRunningTime: "<<atRunningTime()<<"milliseconds.";
qDebug()<<"constAtRunningTime: "<<constAtRunningTime()<<"milliseconds.";
qDebug()<<"squareOperationRunningTime: "<<squareOperationRunningTime()<<"milliseconds.";
qDebug()<<"constSquareOperationRunningTime: "<<constSquareOperationRunningTime()<<"milliseconds.";
return 0;
}