C++真的比Python更快吗?
引言
某些刷题系统超时时间卡得很严格,同一道题目,相同算法,用 python 写就会超时,用 C++ 写就能AC。
这不仅引发进一步思考:C++ 是不是绝对比 python 快,究竟快多少?
实验测试
有人说 C++ 比 Python快几十倍,有人说快上百倍,不如直接来进行实验测试。
1. 简单计算场景
任务:计算从 1 到 N 的所有整数的平方和
N 取值为100万:
python代码:
import timedef sum_of_squares(n):total = 0for i in range(1, n + 1):total += i * ireturn totalif __name__ == "__main__":N = 1000000start = time.time()result = sum_of_squares(N)end = time.time()print("Result:", result)print("Time (Python):", end - start, "seconds")
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;
}
运行时间:
Time (Python): 0.06529355049133301 seconds
Time (C++): 0.0010278 seconds
C++ 的速度约是 python 的 65 倍。
如果 N 取值为 1000万:
输出时间:
Time (C++): 0.0167507 seconds
Time (Python): 0.6048719882965088 seconds
C++ 的速度约是 python 的 36 倍。
2. 包含IO场景的测试
写一个包含100万条的信息的日志文件。
python代码
import timedef 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 = 1000000filename = "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++代码
#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两种方式。
import time
import random
import numpy as npN = 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.0for 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++代码
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;int main() {int N = 300; // 矩阵大小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));srand(time(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;}}clock_t start = clock();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;}}clock_t end = clock();cout << "Time (C++): " << (double)(end - start) / CLOCKS_PER_SEC << " seconds\n";return 0;
}
结果
Time (Python triple loop): 3.641190 seconds
Time (NumPy): 0.000746 seconds
Time (C++): 0.207 seconds
C++ 的速度约是 python 相同写法的 17 倍,但使用numpy之后,python的速度约是C++的 277 倍。
总结
一般情况下,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 更多,但需要的操作会更繁琐。在比较运行效率时,需要考虑测试场景和代码质量。