版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/nicai_xiaoqinxi/article/details/91050289
看看谁的速度快?
环境
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(); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
测试源码
#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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
————————————————
版权声明:本文为CSDN博主「Qt君」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/nicai_xiaoqinxi/article/details/91050289