Mingw GDB导致程序运行慢问题
不要通过GDB/WinDbg启动exe进程,通过命令行/手动双击exe启动程序后,用调试器+PID附加的方式(gdb -p <PID>)可以规避运行慢问题。
ntdll.dll在运行时会判断当前进程是直接启动还是以调试器方式启动,以调试器方式启动时有些API会不一样。
这是最小复现代码,给QList插入1000W条数据:
#include <QCoreApplication> #include <QDateTime> #include <QDebug> struct RecordTestData{ qint32 id,isChip,rows,cols,data,state,chipType; }; void t1() { QList<RecordTestData> datas; for(int i = 0; i < 10000 * 1000; i++) { RecordTestData item; datas.append(item); } } int main() { qDebug() << "start."; auto start = QDateTime::currentMSecsSinceEpoch(); t1(); qDebug() << "end, time:" << (QDateTime::currentMSecsSinceEpoch() - start) << "ms"; }
t1尝试给QList 插入1000W条RecordTestData结构体,主要耗时花在t1函数结束后释放datas(1000W数据)上。
如果直接运行,结果如下:
start. end, time: 542 ms
gdb运行:
(gdb) run Starting program: D:\Work\C++Work\build-ConsoleDemo2-Qt_5_9_8_mingw53_32-Release\release\1\ConsoleDemo2.exe [New Thread 24192.0xa208] [New Thread 24192.0x7c18] [New Thread 24192.0xa9a4] start. end, time: 58850 ms [Thread 24192.0xa9a4 exited with code 0] [Thread 24192.0x7c18 exited with code 0] [Thread 24192.0xa208 exited with code 0] [Inferior 1 (process 24192) exited normally] (gdb)
运行耗时相差巨大!(542ms Vs 58850ms)。
微调程序,通过GDB附加:
#include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <iostream> #ifdef Q_OS_WIN # include <conio.h> // _getch() #else # include <termios.h> # include <unistd.h> #endif struct RecordTestData{ qint32 id,isChip,rows,cols,data,state,chipType; }; void t1() { QList<RecordTestData> datas; for(int i = 0; i < 10000 * 1000; i++) { RecordTestData item; datas.append(item); } } void pauseConsole() { std::cout << "按任意键继续...\n" << std::flush; #ifdef Q_OS_WIN _getch(); // 无回显 #else termios oldt{}; tcgetattr(STDIN_FILENO, &oldt); termios newt = oldt; newt.c_lflag &= ~ECHO; // 关闭回显 tcsetattr(STDIN_FILENO, TCSANOW, &newt); getchar(); // 读取一个字符 tcsetattr(STDIN_FILENO, TCSANOW, &oldt); #endif } int main() { pauseConsole(); qDebug() << "start."; auto start = QDateTime::currentMSecsSinceEpoch(); t1(); qDebug() << "end, time:" << (QDateTime::currentMSecsSinceEpoch() - start) << "ms"; }
结果:
D:\Work\C++Work\build-ConsoleDemo2-Qt_5_9_8_mingw53_32-Release\release\1>ConsoleDemo2.exe 鎸変换鎰忛敭缁х画... start. end, time: 534 ms D:\Work\C++Work\build-ConsoleDemo2-Qt_5_9_8_mingw53_32-Release\release\1>
推荐看这个资料: 为什么gdb在Windows中速度这么慢?-腾讯云开发者社区-腾讯云

然后详细看这个内容,会有更多的收获。http://preshing.com/20110717/the-windows-heap-is-slow-when-launched-from-the-debugger/
在项目中经常需要GDB调试,发现同一个EXE程序通过GDB启动程序和命令行/直接双击EXE启动程序运行速度不一样。
浙公网安备 33010602011771号