C++ 性能优化实战:从内存到 CPU 的执行效率提升
在 C++ 开发中,写出能跑的代码只是第一步,写出高效的代码才是工程师的基本功。很多时候,程序慢不是因为算法复杂度太高,而是细节没处理好。今天我们来聊聊如何系统地提升 C++ 代码的执行效率。
核心原则:先测量后动手
优化不是拍脑袋决定的。很多新手容易陷入过早优化的陷阱,结果改了一堆代码,性能却没提升多少。记住几个铁律:
- 先测量后优化:用工具找出真正的瓶颈,别猜。
- 优化瓶颈:只关注那 20% 影响最大的代码。
- 保持可维护性:别为了快一点点把代码写得像天书。
- 测试验证:优化完必须回归测试,确保逻辑没崩。
常用的分析工具有 GProf、Valgrind、Perf(Linux)以及 Visual Studio Profiler(Windows)。选一个顺手的,跑起来看看数据。
内存管理优化
内存是性能的隐形杀手。泄漏和碎片会让程序在运行一段时间后变慢甚至崩溃。
智能指针与内存泄漏
手动 new 和 delete 很容易出错。现代 C++ 推荐使用智能指针,让 RAII 机制帮你管理生命周期。
#include <iostream>
#include <memory>
// 使用智能指针避免内存泄漏
class MyClass {
public:
MyClass() { std::cout << "MyClass 构造函数" << std::endl; }
~MyClass() { std::cout << "MyClass 析构函数" << std::endl; }
void doSomething() { std::cout << "MyClass 正在做某事" << std::endl; }
};
// 使用智能指针
void useSmartPointer() {
std::shared_ptr<MyClass> ptr = std::make_shared<MyClass>();
ptr->doSomething();
// 离开作用域自动释放,无需手动 delete
}
// 手动管理内存(可能导致泄漏)
void useManualMemory() {
MyClass* ptr = new MyClass();
ptr->doSomething();
// 忘记调用 delete,导致内存泄漏
}
int main() {
std::cout << "=== 内存管理优化示例 ===" << std::endl;
std::cout << "使用智能指针:" << std::endl;
useSmartPointer();
std::cout << std::endl;
std::cout << "手动管理内存:" << std::endl;
useManualMemory();
return 0;
}
减少内存碎片
频繁分配释放小对象会导致内存碎片化。对于 std::vector,如果知道大概容量,提前 reserve 能避免多次扩容带来的拷贝开销。
#include <iostream>
#include <vector>
#include <chrono>
// 预分配内存避免内存碎片
void preallocateMemory() {
const int size = 10000;
std::vector<int> vec;
vec.reserve(size); // 预分配内存
for (int i = 0; i < size; ++i) {
vec.push_back(i);
}
}
// 不预分配内存(可能导致多次扩容)
void notPreallocateMemory() {
const int size = 10000;
std::vector<int> vec;
for (int i = 0; i < size; ++i) {
vec.push_back(i);
}
}
int main() {
std::cout << "=== 内存碎片优化示例 ===" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
preallocateMemory();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "预分配内存耗时:" << duration << "微秒" << std::endl;
start = std::chrono::high_resolution_clock::now();
notPreallocateMemory();
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "不预分配内存耗时:" << duration << "微秒" << std::endl;
return 0;
}
CPU 优化技巧
CPU 层面的优化主要集中在指令流水线和缓存命中率上。
循环优化
合并循环可以减少遍历次数,降低分支预测失败的概率。
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
// 优化循环:合并操作
void optimizedLoop() {
const int size = 10000;
std::vector<int> vec1(size, 1);
std::vector<int> vec2(size, 2);
std::vector<int> result(size, 0);
for (int i = 0; i < size; ++i) {
result[i] = vec1[i] + vec2[i];
}
}
// 未优化的循环:多次遍历
void unoptimizedLoop() {
const int size = 10000;
std::vector<int> vec1(size, 1);
std::vector<int> vec2(size, 2);
std::vector<int> result(size, 0);
for (int i = 0; i < size; ++i) {
result[i] = vec1[i];
}
for (int i = 0; i < size; ++i) {
result[i] += vec2[i];
}
}
int main() {
std::cout << "=== 循环优化示例 ===" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
optimizedLoop();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "优化循环耗时:" << duration << "微秒" << std::endl;
start = std::chrono::high_resolution_clock::now();
unoptimizedLoop();
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "未优化循环耗时:" << duration << "微秒" << std::endl;
return 0;
}
内联函数
对于短小的函数,使用 inline 关键字可以消除函数调用的栈帧开销。不过编译器通常会自动优化,显式声明时注意不要滥用,否则会增加代码体积。
#include <iostream>
#include <vector>
#include <chrono>
// 优化函数:使用内联函数
inline int add(int a, int b) {
return a + b;
}
// 未优化的函数:普通函数调用
int addNotInline(int a, int b) {
return a + b;
}
// 测试函数调用开销
void testFunctionCallOverhead() {
const int size = 1000000;
int result = 0;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < size; ++i) {
result += add(i, i);
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "内联函数调用耗时:" << duration << "微秒" << std::endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < size; ++i) {
result += addNotInline(i, i);
}
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "普通函数调用耗时:" << duration << "微秒" << std::endl;
}
int main() {
std::cout << "=== 函数优化示例 ===" << std::endl;
testFunctionCallOverhead();
return 0;
}
I/O 操作优化
I/O 往往是系统中最慢的部分,尤其是文件和网络读写。
文件 I/O
默认情况下 ofstream 有缓冲区,但有时禁用缓冲或调整缓冲策略能提升特定场景下的写入速度。注意这里演示的是关闭缓冲的极端情况,通常保留缓冲更好。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <chrono>
// 优化文件 I/O:调整缓冲区策略
void optimizedFileIO() {
const std::string filename = "test.txt";
const int size = 10000;
std::ofstream file(filename);
file.rdbuf()->pubsetbuf(nullptr, 0); // 禁用缓冲,视具体需求而定
for (int i = 0; i < size; ++i) {
file << i << std::endl;
}
file.close();
}
// 未优化的文件 I/O:使用默认缓冲区
void unoptimizedFileIO() {
const std::string filename = "test.txt";
const int size = 10000;
std::ofstream file(filename);
for (int i = 0; i < size; ++i) {
file << i << std::endl;
}
file.close();
}
int main() {
std::cout << "=== 文件 I/O 优化示例 ===" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
optimizedFileIO();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "优化文件 I/O 耗时:" << duration << "微秒" << std::endl;
start = std::chrono::high_resolution_clock::now();
unoptimizedFileIO();
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "未优化文件 I/O 耗时:" << duration << "微秒" << std::endl;
return 0;
}
网络 I/O
异步 IO 能让线程在等待网络响应时去处理其他任务,大幅提升吞吐量。这里以 Boost.Asio 为例展示异步与同步的区别。
#include <iostream>
#include <vector>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read_until.hpp>
#include <sstream>
#include <exception>
#include <chrono>
using boost::asio::ip::tcp;
using namespace std;
// 优化网络 I/O:使用异步操作
void optimizedNetworkIO() {
try {
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("example.com", "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
std::string request = "GET / HTTP/1.1\r\n";
request += "Host: example.com\r\n";
request += "Connection: close\r\n\r\n";
boost::asio::write(socket, boost::asio::buffer(request));
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
string status_line;
istringstream response_stream(&response);
response_stream >> status_line;
} catch (const std::exception& e) {
cerr << "错误:" << e.what() << endl;
}
}
// 未优化的网络 I/O:使用同步操作
void unoptimizedNetworkIO() {
try {
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("example.com", "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
std::string request = "GET / HTTP/1.1\r\n";
request += "Host: example.com\r\n";
request += "Connection: close\r\n\r\n";
boost::asio::write(socket, boost::asio::buffer(request));
string response;
char buffer[1024];
size_t len;
while ((len = socket.read_some(boost::asio::buffer(buffer))) > 0) {
response.append(buffer, len);
}
} catch (const std::exception& e) {
cerr << "错误:" << e.what() << endl;
}
}
int main() {
std::cout << "=== 网络 I/O 优化示例 ===" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
optimizedNetworkIO();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "优化网络 I/O 耗时:" << duration << "毫秒" << std::endl;
start = std::chrono::high_resolution_clock::now();
unoptimizedNetworkIO();
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "未优化网络 I/O 耗时:" << duration << "毫秒" << std::endl;
return 0;
}
综合案例:矩阵乘法优化
最后来看个实际点的例子。矩阵乘法是计算密集型任务的典型代表,优化空间很大。
项目结构
MatrixMultiplicationOptimization/
├── include/
│ └── Matrix.h
├── src/
│ ├── Matrix.cpp
│ └── main.cpp
└── build/
核心代码
// include/Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
#include <chrono>
#include <stdexcept>
using namespace std;
using namespace chrono;
class Matrix {
public:
Matrix(int rows, int cols);
Matrix(const vector<vector<int>>& data);
int getRows() const;
int getCols() const;
int& operator()(int row, int col);
const int& operator()(int row, int col) const;
Matrix multiplyNaive(const Matrix& other) const;
Matrix multiplyOptimized(const Matrix& other) const;
void print() const;
vector<vector<int>> getTransposed() const;
private:
int rows_;
int cols_;
vector<vector<int>> data_;
};
#endif // MATRIX_H
// src/Matrix.cpp
#include "Matrix.h"
#include <iostream>
Matrix::Matrix(int rows, int cols)
: rows_(rows), cols_(cols), data_(rows, vector<int>(cols, 0)) {}
Matrix::Matrix(const vector<vector<int>>& data)
: rows_(data.size()), cols_(data[0].size()), data_(data) {}
int Matrix::getRows() const { return rows_; }
int Matrix::getCols() const { return cols_; }
int& Matrix::operator()(int row, int col) {
return data_[row][col];
}
const int& Matrix::operator()(int row, int col) const {
return data_[row][col];
}
Matrix Matrix::multiplyNaive(const Matrix& other) const {
if (cols_ != other.rows_) {
throw invalid_argument("矩阵尺寸不兼容");
}
Matrix result(rows_, other.cols_);
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < other.cols_; ++j) {
for (int k = 0; k < cols_; ++k) {
result(i, j) += data_[i][k] * other.data_[k][j];
}
}
}
return result;
}
Matrix Matrix::multiplyOptimized(const Matrix& other) const {
if (cols_ != other.rows_) {
throw invalid_argument("矩阵尺寸不兼容");
}
Matrix result(rows_, other.cols_);
vector<vector<int>> otherTransposed = other.getTransposed();
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < other.cols_; ++j) {
int sum = 0;
for (int k = 0; k < cols_; ++k) {
sum += data_[i][k] * otherTransposed[j][k];
}
result(i, j) = sum;
}
}
return result;
}
vector<vector<int>> Matrix::getTransposed() const {
vector<vector<int>> transposed(cols_, vector<int>(rows_));
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
transposed[j][i] = data_[i][j];
}
}
return transposed;
}
void Matrix::print() const {
for (const auto& row : data_) {
for (int value : row) {
cout << value << " ";
}
cout << endl;
}
}
// src/main.cpp
#include <iostream>
#include <vector>
#include <chrono>
#include "Matrix.h"
using namespace std;
using namespace chrono;
int main() {
std::cout << "=== 矩阵乘法优化示例 ===" << std::endl;
const int size = 100;
Matrix matrix1(size, size);
Matrix matrix2(size, size);
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
matrix1(i, j) = i + j;
matrix2(i, j) = i * j;
}
}
auto start = high_resolution_clock::now();
Matrix resultNaive = matrix1.multiplyNaive(matrix2);
auto end = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(end - start).count();
std::cout << "朴素算法耗时:" << duration << "毫秒" << std::endl;
start = high_resolution_clock::now();
Matrix resultOptimized = matrix1.multiplyOptimized(matrix2);
end = high_resolution_clock::now();
duration = duration_cast<milliseconds>(end - start).count();
std::cout << "优化算法耗时:" << duration << "毫秒" << std::endl;
return 0;
}
构建与运行
# 创建构建目录
mkdir -p build && cd build
# 配置 CMake
cmake -DCMAKE_BUILD_TYPE=Release ..
# 编译项目
cmake --build . --config Release
# 运行程序
./MatrixMultiplicationOptimization
总结
性能优化没有银弹,它需要结合具体的业务场景。通过智能指针管理内存,利用向量预分配减少碎片,合并循环减少遍历,以及合理选择同步或异步 IO,都能带来可观的提升。矩阵乘法的例子展示了如何通过转置优化缓存局部性。建议大家在日常开发中多使用性能分析工具,养成'先测量,后优化'的习惯。

