【1】多重循环编码规范
在多重循环中,必须将最忙的循环放在最内层,以减少CPU切入循环层的次数。
【2】示例代码
1、新建QT默认工程
2、源码
(1)pro文件
1 QT += core gui 2 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 4 5 TARGET = TestTime 6 TEMPLATE = app 7 8 9 SOURCES += main.cpp10 mainwindow.cpp 11 12 HEADERS += mainwindow.h 13 14 FORMS += mainwindow.ui
(2)mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 6 namespace Ui 7 { 8 class MainWindow; 9 } 10 11 class MainWindow : public QMainWindow 12 { 13 Q_OBJECT 14 15 public: 16 explicit MainWindow(QWidget *parent = 0); 17 ~MainWindow(); 18 19 void Test(); 20 21 private: 22 void result(); 23 void doSomething(); 24 void TestMaxOuter(); 25 void TestMaxInner(); 26 27 private: 28 Ui::MainWindow *ui; 29 int m_timeMaxOuter; 30 int m_timeMaxInner; 31 }; 32 33 #endif // MAINWINDOW_H
(3)mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 #include <QTime> 4 #include <QDebug> 5 6 #define CYCLE_TIMES1 (10) 7 #define CYCLE_TIMES2 (100) 8 #define CYCLE_TIMES3 (1000) 9 10 MainWindow::MainWindow(QWidget *parent) 11 : QMainWindow(parent), 12 ui(new Ui::MainWindow), 13 m_timeMaxOuter(0), 14 m_timeMaxInner(0) 15 { 16 ui->setupUi(this); 17 } 18 19 MainWindow::~MainWindow() 20 { 21 delete ui; 22 } 23 24 void MainWindow::Test() 25 { 26 TestMaxOuter(); 27 TestMaxInner(); 28 result(); 29 } 30 31 void MainWindow::doSomething() 32 { 33 for (int i = 0; i < CYCLE_TIMES2; ++i) 34 { 35 int *pTemp = new int; 36 *pTemp = i; 37 delete pTemp; 38 } 39 } 40 41 void MainWindow::TestMaxOuter() 42 { 43 QTime timeTemp; 44 timeTemp.start(); 45 46 for (int i = 0; i < CYCLE_TIMES3; ++i) 47 { 48 for (int j = 0; j < CYCLE_TIMES2; ++j) 49 { 50 for (int m = 0; m < CYCLE_TIMES1; ++m) 51 { 52 doSomething(); 53 } 54 } 55 } 56 57 m_timeMaxOuter = timeTemp.elapsed(); 58 qDebug() << "TestMaxOuter cost time :: " << m_timeMaxOuter; 59 } 60 61 void MainWindow::TestMaxInner() 62 { 63 QTime timeTemp; 64 timeTemp.start(); 65 66 for (int i = 0; i < CYCLE_TIMES1; ++i) 67 { 68 for (int j = 0; j < CYCLE_TIMES2; ++j) 69 { 70 for (int m = 0; m < CYCLE_TIMES3; ++m) 71 { 72 doSomething(); 73 } 74 } 75 } 76 77 m_timeMaxInner = timeTemp.elapsed(); 78 qDebug() << "TestMaxInner cost time :: " << m_timeMaxInner; 79 } 80 81 void MainWindow::result() 82 { 83 if (m_timeMaxInner < m_timeMaxOuter) 84 { 85 qDebug() << "MaxInner more than faster :: " << m_timeMaxOuter - m_timeMaxInner; 86 } 87 else 88 { 89 qDebug() << "MaxOuter more than faster :: " << m_timeMaxInner - m_timeMaxOuter; 90 } 91 }
(4)main.cpp
1 #include "mainwindow.h" 2 #include <QApplication> 3 4 int main(int argc, char *argv[]) 5 { 6 QApplication a(argc, argv); 7 MainWindow w; 8 w.Test(); 9 w.show(); 10 11 return a.exec(); 12 }
3、运行结果
【3】总结
循环越少越好。如果使用循环,注意循环顺序的内在效率。
Good Good Study, Day Day Up.
顺序 选择 循环 总结