C++ 性能优化实战:从内存到 CPU 的执行效率提升
性能优化不是玄学,而是对资源调度的精细掌控。很多时候,代码能跑通只是第一步,真正决定系统上限的是执行效率。本章我们将深入探讨 C++ 性能优化的核心知识,帮你掌握提升代码执行效率的艺术。
性能优化的基本原则
盲目优化往往适得其反。在动手之前,请遵循几个铁律:先测量后优化,找出瓶颈所在;只优化对性能影响最大的部分;保持代码的可维护性,别让优化后的代码变成天书;最后,测试优化结果,确保正确性和提升效果。
常用的分析工具包括 GProf、Valgrind、Perf 以及 Visual Studio Profiler,它们能帮你定位热点代码。
内存管理优化
内存是性能的大敌之一。
智能指针与内存泄漏
手动管理内存容易出错,智能指针是现代 C++ 的首选。它能自动处理生命周期,避免常见的悬空指针和泄漏问题。
#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;
}
减少内存碎片
频繁的小块分配会导致碎片化,预分配空间是个好习惯。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 优化技巧
循环优化
合并循环可以减少遍历次数,提高指令缓存命中率。将多个操作合并到一个循环中,通常比分开遍历更高效。
#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 优化
默认的文件流可能带有缓冲,但在某些高吞吐场景下,调整缓冲区策略能带来显著差异。禁用缓冲或自定义缓冲大小取决于具体需求。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <chrono>
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();
}
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 优化
异步 I/O 允许程序在等待网络响应时继续处理其他任务,特别适合高并发场景。Boost.Asio 提供了强大的异步支持。
#include <iostream>
#include <vector>
#include <string>
#include <boost/asio.hpp>
#include <chrono>
#include <sstream>
using boost::asio::ip::tcp;
using namespace std;
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;
}
}
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;
}
综合案例:矩阵乘法优化
在实际项目中,算法层面的优化往往比微观指令更有效。这里以矩阵乘法为例,展示如何通过数据布局优化来提升性能。
核心逻辑
朴素算法直接按行主序访问,而优化版本通过转置第二个矩阵,使访问模式更符合 CPU 缓存的行局部性原理。
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
#include <chrono>
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;
private:
int rows_;
int cols_;
vector<vector<int>> data_;
};
#endif // MATRIX_H
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;
}
}
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;
}
构建与运行
使用 CMake 构建项目:
mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build . --config Release
./MatrixMultiplicationOptimization
结语
性能优化是一个持续的过程。记住,先测量再行动,关注瓶颈,保持代码清晰。通过理解内存模型、CPU 特性和 I/O 机制,你可以写出既高效又优雅的 C++ 代码。后续可以尝试 SIMD 指令集、并发编程或内存池等进阶技术,进一步挖掘硬件潜力。


