C++真的比Python更快吗?

引言

某些刷题系统超时时间卡得很严格,同一道题目,相同算法,用 python 写就会超时,用 C++ 写就能AC。

这不仅引发进一步思考:C++ 是不是绝对比 python 快,究竟快多少?

实验测试

有人说 C++ 比 Python快几十倍,有人说快上百倍,不如直接来进行实验测试。

1. 简单计算场景

任务:计算从 1 到 N 的所有整数的平方和

N 取值为100万:

python代码:

python 复制代码
import time

def sum_of_squares(n):
    total = 0
    for i in range(1, n + 1):
        total += i * i
    return total

if __name__ == "__main__":
    N = 1000000
    start = time.time()
    result = sum_of_squares(N)
    end = time.time()
    print("Result:", result)
    print("Time (Python):", end - start, "seconds")

C++代码:

c 复制代码
#include <iostream>
#include <chrono>
using namespace std;

long long sum_of_squares(int n) {
    long long total = 0;
    for (int i = 1; i <= n; i++) {
        total += 1LL * i * i;
    }
    return total;
}

int main() {
    int N = 1000000;
    auto start = chrono::high_resolution_clock::now();
    long long result = sum_of_squares(N);
    auto end = chrono::high_resolution_clock::now();
    chrono::duration<double> elapsed = end - start;
    cout << "Result: " << result << endl;
    cout << "Time (C++): " << elapsed.count() << " seconds" << endl;
    return 0;
}

运行时间:

bash 复制代码
Time (Python): 0.06529355049133301 seconds
Time (C++): 0.0010278 seconds

C++ 的速度约是 python 的 65 倍。

如果 N 取值为 1000万:

输出时间:

bash 复制代码
Time (C++): 0.0167507 seconds
Time (Python): 0.6048719882965088 seconds

C++ 的速度约是 python 的 36 倍。

2. 包含IO场景的测试

写一个包含100万条的信息的日志文件。

python代码

python 复制代码
import time

def generate_log_file(filename, n):
    with open(filename, "w") as f:
        for i in range(n):
            f.write(f"[INFO] line {i}: this is a test log message\n")

if __name__ == "__main__":
    N = 1000000
    filename = "log_python.txt"

    start = time.perf_counter()
    generate_log_file(filename, N)
    end = time.perf_counter()

    print(f"Generated {N} lines into {filename}")
    print("Time (Python):", end - start, "seconds")

C++代码

cpp 复制代码
#include <iostream>
#include <fstream>
#include <chrono>
using namespace std;

void generate_log_file(const string &filename, int n) {
    ofstream fout(filename);
    for (int i = 0; i < n; i++) {
        fout << "[INFO] line " << i << ": this is a test log message\n";
    }
    fout.close();
}

int main() {
    int N = 1000000;
    string filename = "log_cpp.txt";

    auto start = chrono::high_resolution_clock::now();
    generate_log_file(filename, N);
    auto end = chrono::high_resolution_clock::now();
    chrono::duration<double> elapsed = end - start;

    cout << "Generated " << N << " lines into " << filename << endl;
    cout << "Time (C++): " << elapsed.count() << " seconds" << endl;
    return 0;
}

结果

复制代码
Time (Python): 0.6496610003523529 seconds
Time (C++): 0.442306 seconds

受到磁盘写入速度的限制,在 IO 场景下,C++ 的速度仅为是 python 的 1.46 倍。

3. 矩阵密集计算

下面再测试一个矩阵相乘的计算场景。

python代码,测试普通循环和使用numpy两种方式。

python 复制代码
import time
import random
import numpy as np

N = 300  # 矩阵大小

# 用 Python 列表生成矩阵
A = [[random.random() for _ in range(N)] for _ in range(N)]
B = [[random.random() for _ in range(N)] for _ in range(N)]

# ---------- Python 三重循环 ----------
start = time.perf_counter()
C = [[0.0] * N for _ in range(N)]
for i in range(N):
    for j in range(N):
        s = 0.0
        for k in range(N):
            s += A[i][k] * B[k][j]
        C[i][j] = s
end = time.perf_counter()
print(f"Time (Python triple loop): {end - start:.6f} seconds")

# ---------- NumPy 实现 ----------
A_np = np.array(A)
B_np = np.array(B)

start = time.perf_counter()
C_np = np.dot(A_np, B_np)
end = time.perf_counter()
print(f"Time (NumPy): {end - start:.6f} seconds")

C++代码,测试普通循环、使用Eigen和使用BLAS三种方式:

cpp 复制代码
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <Eigen/Dense>
#include <cblas.h>

using namespace std;
using namespace Eigen;

// ================= 原生 C++ 三重循环 =================
void naiveMultiply(const vector<vector<double>>& A,
                   const vector<vector<double>>& B,
                   vector<vector<double>>& C, int N) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            double s = 0.0;
            for (int k = 0; k < N; k++) {
                s += A[i][k] * B[k][j];
            }
            C[i][j] = s;
        }
    }
}

// ================= 结果验证 =================
bool checkResult(const MatrixXd& C1, const MatrixXd& C2, double tol = 1e-8) {
    if (C1.rows() != C2.rows() || C1.cols() != C2.cols()) return false;
    for (int i = 0; i < C1.rows(); i++) {
        for (int j = 0; j < C1.cols(); j++) {
            if (fabs(C1(i,j) - C2(i,j)) > tol) return false;
        }
    }
    return true;
}

int main() {
    int N = 300;  // 矩阵大小

    // 随机数初始化
    srand(time(0));

    // ====== 生成矩阵 ======
    vector<vector<double>> A(N, vector<double>(N));
    vector<vector<double>> B(N, vector<double>(N));
    vector<vector<double>> C(N, vector<double>(N, 0.0));

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            A[i][j] = rand() / (double)RAND_MAX;
            B[i][j] = rand() / (double)RAND_MAX;
        }
    }

    // ====== Naive C++ ======
    clock_t start = clock();
    naiveMultiply(A, B, C, N);
    clock_t end = clock();
    cout << "Time (Naive C++): " << (double)(end - start) / CLOCKS_PER_SEC << " seconds\n";

    // 转成 Eigen 矩阵
    MatrixXd EA(N, N), EB(N, N), EC(N, N);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            EA(i, j) = A[i][j];
            EB(i, j) = B[i][j];
        }
    }

    // ====== Eigen ======
    start = clock();
    EC = EA * EB;
    end = clock();
    cout << "Time (Eigen): " << (double)(end - start) / CLOCKS_PER_SEC << " seconds\n";

    // ====== BLAS (cblas_dgemm) ======
    vector<double> A1D(N * N), B1D(N * N), C1D(N * N, 0.0);
    // 转换为列主序 (BLAS 默认列主序)
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            A1D[j * N + i] = A[i][j];
            B1D[j * N + i] = B[i][j];
        }
    }

    start = clock();
    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
                N, N, N, 1.0,
                A1D.data(), N,
                B1D.data(), N,
                0.0,
                C1D.data(), N);
    end = clock();
    cout << "Time (BLAS dgemm): " << (double)(end - start) / CLOCKS_PER_SEC << " seconds\n";
    
    return 0;
}

结果:

复制代码
Time (Python triple loop): 3.641190 seconds
Time (NumPy): 0.000746 seconds
Time (Naive C++): 0.206 seconds
Time (Eigen): 0.224 seconds
Time (BLAS dgemm): 0.001 seconds

普通模式情况下,C++的速度确实比python快,但python使用NumPy之后,速度可以接近C++使用BLAS ,C++的Eigen库并不能带来加速效果,可能和操作系统有关,测试所用的操作系统为win10。

总结

一般情况下,C++ 确实比 Python 会快很多,在普通计算效率上,至少有10倍以上的提升,主要原因是语言本身的差异性:

  • C++ 是编译型语言,源代码会被编译为机器码,直接在 CPU 上运行,几乎没有额外的解释开销。
  • Python 是解释型语言,运行时需要解释器逐行执行代码,每一步操作都要经过额外的对象管理和动态类型检查,计算效率天然落后。

但是,当任务涉及文件写入、磁盘读写或网络通信 时,性能瓶颈转移到操作系统和硬件的 IO 延迟上,两者的速度差异会减小。

此外,Python在借 助NumPy 等第三库之后,计算效率反而比未经优化的C++速度更快,主要原因是 Numpy 的矩阵乘法核心调用了底层 C/Fortran 的 BLAS/LAPACK 库,这些库经过几十年的优化,包含一系列优化策略:

  • 循环展开、SIMD 向量化(利用 SSE/AVX 指令集,一次处理多个数据);
  • Cache 优化(分块算法 block matrix multiplication,减少 cache miss);
  • 多线程并行(OpenBLAS/MKL 可以利用多核 CPU 并行计算);
  • 硬件加速(在某些场景下甚至能利用 GPU)。

因此,直接认为 C++ 比 Python 快是不准确的,C++ 的优化空间会比 Python 更多,但需要的操作会更繁琐。在比较运行效率时,需要考虑测试场景和代码质量。

相关推荐
Jack电子实验室3 小时前
实用工具:基于Python的图片定位导出小程序
java·python·小程序
j_xxx404_3 小时前
C++:入门基础(2)
开发语言·c++
yuec3 小时前
iOS 系统获取 C++ 崩溃堆栈 - 撒花完结篇
c++·ios
CodeCraft Studio3 小时前
借助Aspose.HTML控件,使用 Python 编程创建 HTML 页面
前端·python·html·aspose·python创建html·html sdk
yolo_guo4 小时前
glog使用: 07-错误信号处理(Failure Signal Handler)
linux·c++·glog
小蕾Java4 小时前
Python开发最新 PyCharm 2025使用(附详细教程)
ide·python·pycharm
林文韬3274 小时前
C、C++、Java 和 Python:四大编程语言的对比分析
java·c语言·c++·python
B站_计算机毕业设计之家4 小时前
✅ Python房源数据采集+分析+预测平台 requests爬虫+sklearn回归 大数据实战项目(建议收藏)机器学习(附源码)
大数据·爬虫·python·机器学习·数据采集·sklearn·房源