在 Linux 下用 C++ 写程序“运行缓慢”,原因可能非常多,不一定和语言本身有关。下面按常见原因分类说明,并给出排查思路。
O(n^2) 甚至更差std::list / map 而不是 vector / unordered_map✅ 建议:
vector 代替 listunordered_mapcout、printf✅ 建议:
// 关闭同步,提高 cout 速度
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
fstream + 缓冲✅ 建议:
std::vector::reservenewstd::vector<int> v;
v.reserve(1000000);
std::string 拷贝✅ 建议:
void f(const std::string& s);
mutex 使用不当✅ 建议:
atomic✅ 建议:
g++ main.cpp
✅ 正确方式:
g++ -O2 main.cpp
# 或
g++ -O3 -march=native main.cpp
-g + 未优化_GLIBCXX_DEBUG)✅ 建议:
top / htop 查看read/write 太频繁sleep 不合理✅ 建议:
epolltop
htop
perf top
perf record ./a.out
perf report
valgrind --tool=callgrind ./a.out
或代码中打时间点:
auto t = std::chrono::high_resolution_clock::now();
C++ 本身不慢,慢的是:算法、I/O、内存、锁、编译器选项和系统调用。
如果你愿意,可以把:
发出来,我可以帮你具体定位是哪一类问题。