- 创建完整的多线程性能测试套件,用于对比单线程、GIL多线程和NoGIL多线程的性能差异 - 实现三种测试模式:单线程测试、传统GIL多线程测试、无GIL多线程测试 - 添加质数查找算法作为CPU密集型测试用例,支持可配置的质数数量和线程数 - 提供详细的性能对比报告,包括执行时间、相对速度倍数和找到的质数数量 - 支持详细日志输出模式,可实时查看各线程的执行状态 - 包含项目配置文件:pyproject.toml、.gitignore、.python-version和MIT许可证 - 采用模块化设计,将不同测试策略分离到独立模块中便于维护
52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
# src/nogil_thread.py
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
from .primes import is_prime
|
||
import sys
|
||
|
||
def _find_primes_in_range(start, end, thread_id, verbose):
|
||
"""
|
||
在指定范围内寻找质数(无共享状态,适合NoGIL)。
|
||
"""
|
||
primes = []
|
||
# 从奇数开始检查,提高效率
|
||
candidate = start if start % 2 == 1 else start + 1
|
||
while candidate < end:
|
||
if is_prime(candidate):
|
||
primes.append(candidate)
|
||
if verbose and len(primes) % 1000 == 0:
|
||
print(f"[线程-{thread_id}] 已找到 {len(primes)} 个质数...", file=sys.stderr)
|
||
candidate += 2
|
||
return primes
|
||
|
||
def find_primes_nogil_thread(total_to_find, thread_count, verbose=False):
|
||
"""
|
||
使用多线程(无GIL)寻找指定数量的质数。
|
||
采用静态任务划分策略。
|
||
"""
|
||
# 估算一个足够大的搜索范围来找到 total_to_find 个质数
|
||
import math
|
||
if total_to_find < 6:
|
||
search_limit = 30
|
||
else:
|
||
ln_n = math.log(total_to_find)
|
||
search_limit = int(total_to_find * (ln_n + math.log(ln_n)) * 1.1) # 乘以1.1作为缓冲
|
||
|
||
chunk_size = search_limit // thread_count
|
||
|
||
all_primes = []
|
||
with ThreadPoolExecutor(max_workers=thread_count) as executor:
|
||
futures = []
|
||
for i in range(thread_count):
|
||
start = 2 + i * chunk_size
|
||
# 最后一个线程处理剩余的所有数字
|
||
end = start + chunk_size if i != thread_count - 1 else search_limit
|
||
futures.append(executor.submit(_find_primes_in_range, start, end, i, verbose))
|
||
|
||
for future in futures:
|
||
all_primes.extend(future.result())
|
||
|
||
# 合并结果并排序
|
||
all_primes.sort()
|
||
|
||
# 返回前 total_to_find 个质数
|
||
return all_primes[:total_to_find] |