跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客工具镜像开源精选AI社区
我的书AI 学习话题UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
C++算法

C++ 性能优化实战:从内存到 CPU 的执行效率提升

C++ 性能优化涉及内存管理、CPU 指令及 I/O 策略。通过智能指针防止泄漏,预分配向量减少碎片,合并循环降低开销,利用异步 IO 提升吞吐。矩阵乘法案例展示了缓存局部性优化的实际效果。掌握测量工具与核心原则,方能写出高效代码。

宁静发布于 2026/3/21更新于 2026/12/293 浏览
C++ 性能优化实战:从内存到 CPU 的执行效率提升

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,都能带来可观的提升。矩阵乘法的例子展示了如何通过转置优化缓存局部性。建议大家在日常开发中多使用性能分析工具,养成'先测量,后优化'的习惯。

目录

  1. C++ 性能优化实战:从内存到 CPU 的执行效率提升
  2. 核心原则:先测量后动手
  3. 内存管理优化
  4. 智能指针与内存泄漏
  5. 减少内存碎片
  6. CPU 优化技巧
  7. 循环优化
  8. 内联函数
  9. I/O 操作优化
  10. 文件 I/O
  11. 网络 I/O
  12. 综合案例:矩阵乘法优化
  13. 项目结构
  14. 核心代码
  15. 构建与运行
  16. 创建构建目录
  17. 配置 CMake
  18. 编译项目
  19. 运行程序
  20. 总结

更多推荐文章

查看全部
  • AI 大模型入门教程:从零基础到精通
  • Stable Diffusion 本地部署与基础使用指南
  • 深度学习激活函数完全指南:Sigmoid、Tanh、ReLU 到现代变体
  • MySQL 本地用户查询与密码重置方法
  • openTCS WEB 接口实战:从基础调用到自定义指令开发
  • Tauri 前端框架接入配置指南:Vite/Next/Nuxt/SvelteKit/Leptos
  • Python SQLAlchemy ORM 数据库操作指南:安装、模型与 CRUD
  • 基于 Web 的宠物领养管理系统设计与实现
  • 滑动窗口算法详解:高效解决子数组与子串问题
  • 基于 STM32 的智能家居安防系统设计与实现
  • OpenCode 本地 AI 模型配置指南
  • 微信 H5 缓存控制:后端重定向与前端强制刷新
  • AI 短视频分镜头设计与 AI 绘画提示词入门
  • C++ STL vector 常用函数接口详解
  • JDK8 下载安装与环境变量配置
  • Python turtle 库入门与趣味图形绘制
  • 前端视角下的 Agent 工程化开发学习路线
  • VSCode + Copilot
  • SWE-CI: 基于持续集成评估智能体代码维护能力
  • 飞牛 NAS 部署 OpenWebUI 接入 DeepSeek AI 大模型

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online