多语言性能基准测试

一个简洁的多语言性能基准测试项目,比较不同编程语言在素数查找任务(计算密集型任务)上的执行效率。

🎯 测试目标

寻找 0 到 8,000,000 范围内的所有素数,使用多线程/多进程并行计算。

🚀 支持的语言

  • C99 - 使用 pthread 多线程
  • C++17 - 使用 std::thread 多线程
  • Go - 使用 goroutine 并发
  • Python - 支持 multiprocessing 和 threading
  • Rust - 使用 std::thread 多线程

🏃‍♂️ 快速开始

# 运行完整基准测试
chmod +x run_benchmark_full.sh
./run_benchmark_full.sh

脚本会自动:

  1. 检测可用的编程环境
  2. 编译所有程序
  3. 运行性能测试
  4. 生成性能对比报告

比如在我的 Mac 上,运行结果如下:


===== Programming Language Environment Detection =====

Detecting C/C++ compilers...
✓ Found LLVM Clang: Apple clang version 17.0.0 (clang-1700.0.13.5)
✓ LLVM Clang supports C99 standard
✓ LLVM Clang++ supports C++17 standard

Detecting Golang environment...
✓ Found Golang: go version go1.21.9 darwin/arm64

Detecting Python environment...
✓ Found Python: Python 3.14.0a6

Detecting Rust environment...
✓ Found Rust: rustc 1.89.0 (29483883e 2025-08-04)

===== Environment Detection Summary =====

C99 Support: ✓ Available
C++17 Support: ✓ Available
Golang: ✓ Available
Python: Python 3.14.0a6
Rust: ✓ Available

===== Performance Benchmark: Finding Primes up to 8,000,000 =====

Machine Info:
- CPU: Apple M1
- Cores: 8

===== Compiling Programs... =====

Compiling C99...
Compiling C++17...
Compiling Golang...
Compiling Rust...

===== Running Benchmarks... (This may take a while) =====


===== Performance Comparison Report =====

1. C++17: Found 539777 primes in 0.1242 seconds.
2. C99 (pthreads): Found 539777 primes in 0.1249 seconds.
3. Rust: Found 539777 primes in 0.1294 seconds.
4. Golang: Found 539777 primes in 0.1479 seconds.
5. Python3.14 (multiprocessing): Found 539777 primes in 5.7623 seconds.
6. Python3.10 (multiprocessing): Found 539777 primes in 7.0637 seconds.
7. Python3.14 (threading): Found 539777 primes in 15.7026 seconds.
8. Python3.10 (threading): Found 539777 primes in 19.7169 seconds.

Report generated on: Fri Sep 12 22:46:21 CST 2025

📊 测试算法

所有实现使用相同的优化算法:

  • 跳过偶数(除了2)
  • 只检查到 √n 的因子
  • 使用 6k±1 模式优化循环

📁 项目结构

├── prime_c99/             # C99 实现
├── prime_cpp17/           # C++17 实现  
├── prime_go/              # Go 实现
├── prime_python/          # Python 实现
├── prime_rust/            # Rust 实现
└── run_benchmark_full.sh  # 自动化测试脚本

📈 性能特点

  • 编译型语言 (C/C++/Rust/Go): 通常表现最佳
  • 解释型语言 (Python): 相对较慢但易于开发,Python3.14 的性能比之前的版本要好,因为 Python3.14 的 GIL 锁机制被移除了。
  • 并发模型: 各语言使用最适合的并发机制

基准测试结果会因硬件配置而异,建议在相同环境下进行对比。