当前位置: 首页 > news >正文

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 更多,但需要的操作会更繁琐。在比较运行效率时,需要考虑测试场景和代码质量。


文章转载自:

http://Nnm2c5lN.stsnf.cn
http://lrmhwIVg.stsnf.cn
http://EFQ3rz26.stsnf.cn
http://2iDIz57E.stsnf.cn
http://UhtP1Puv.stsnf.cn
http://IP66o93I.stsnf.cn
http://bujHcRDn.stsnf.cn
http://PKpg1uZU.stsnf.cn
http://f5Lj2uw0.stsnf.cn
http://awWOaoDq.stsnf.cn
http://6knKJL6e.stsnf.cn
http://iSP1xHT0.stsnf.cn
http://TdZFG2pP.stsnf.cn
http://liT2HI1y.stsnf.cn
http://JfOInixp.stsnf.cn
http://Z9CtlwqL.stsnf.cn
http://oYbzQ6mC.stsnf.cn
http://R5P6Qd1X.stsnf.cn
http://qfR2PqGd.stsnf.cn
http://COBovXPK.stsnf.cn
http://hobknpTk.stsnf.cn
http://8yAfcb0T.stsnf.cn
http://rsZ2HeDX.stsnf.cn
http://OtNljwxG.stsnf.cn
http://rwixd8Ie.stsnf.cn
http://bs67qbN5.stsnf.cn
http://g5SAa2JP.stsnf.cn
http://lCFlM7OP.stsnf.cn
http://jzfqhg1i.stsnf.cn
http://yGXHabjj.stsnf.cn
http://www.dtcms.com/a/388412.html

相关文章:

  • 【实操分享】使用 SeeDream 4.0 进行 AI 修图——开启专属“AI 云旅拍”
  • 不依赖第三方,不销毁重建,loveqq 框架如何原生实现动态线程池?
  • Python中正则的三个基础方法
  • 最外层的项目没有父pom配置文件,有很多子模块(maven项目)导入idea中,左侧模块显示不全问题解决
  • 前端将一个 DOM 元素滚动到视口顶部
  • 前端-防重复点击/防抖的方案
  • doris数据库问题
  • PyQt5中实现只读QLineEdit控件的完整指南
  • 金融工程vs金融数学:谁更贴近量化交易?
  • LeetCode 167.两数之和 II - 输入有序数组
  • 小杰机器学习高级(one)——激活函数——sigmoid、tanh、Relu、Leaky Relu、Prelu、ELU、softmax
  • OpenAI原生调用 vs LangChain调用方式的关系
  • [Token剪枝]Token Cropr: 针对众多任务的更快ViT, CVPR2025
  • NW725NW743美光固态闪存NW727NW734
  • 【Linux】归档、压缩、用户管理
  • Lattice FPGA 开发流程(以 ECP5 为例)
  • 大模型实战应用指南:从GPT-4.5到LLaMA的行业解决方案
  • 告别人工标注瓶颈!Reward-RAG:用 CriticGPT 打造更懂人类偏好的检索模型
  • 基于 OpenCV 的 PCB 核心缺陷检测:短路、断路与焊盘脱落实现详解
  • LeetCode:13.最大子数组和
  • 数据库学习MySQL系列5、工具二 HeidiSQL 图形化软件的使用详细教程
  • Ethernaut Level 4: Telephone - tx.origin vs msg.sender 身份验证绕过
  • RWA开启数字时代的文化价值新纪元
  • 【Redis】-- 分布式锁
  • 分布式拜占庭容错算法——实现工作量证明(PoW)算法详解
  • 基础介绍(Solidity、Polkadot)
  • 【Axure高保真原型】智慧水利可视化分析案例
  • oracle的sql语句中 a=b(+),代表什么意思
  • 联邦学习论文分享:
  • Linux渗透中group的利用