Notion Blog
技术分享1 分钟阅读

Python3.14移除全局解释器锁(

测试代码(测试代码AI生成)

import time
import threading
import multiprocessing
import statistics
import random
import math
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import sys

# 优化后的测试配置
CONFIG = {
    'cpu': {
        'fib_size': 32,        # 增大斐波那契计算规模
        'fib_runs': 5,        # 增加计算次数
        'prime_range': 2000000, # 增大素数计算范围
        'prime_runs': 5,       # 增加素数计算次数
        'matrix_size': 300,     # 增加矩阵大小
        'matrix_runs': 5,      # 矩阵计算次数
        'workers': multiprocessing.cpu_count()
    },
    'io': {
        'task_count': 100,
        'base_duration': 0.01,
        'workers': min(50, multiprocessing.cpu_count() * 4)
    },
    'test_repeats': 3,
    'warmup_repeats': 1
}

def cpu_intensive_fib(n):
    """更耗时的斐波那契计算"""
    def fib_recursive(n):
        if n <= 1:
            return n
        return fib_recursive(n-1) + fib_recursive(n-2)
    
    # 多次计算以增加耗时
    result = 0
    for _ in range(5):  # 重复计算5次
        result = fib_recursive(n)
    return result

def is_prime(n):
    """更严格的素数判断"""
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def compute_primes(max_num):
    """计算范围内所有素数,更耗时"""
    primes = []
    for num in range(2, max_num):
        if is_prime(num):
            primes.append(num)
    return primes

def matrix_multiply(size):
    """纯Python矩阵乘法"""
    # 创建大矩阵
    a = [[random.random() for _ in range(size)] for _ in range(size)]
    b = [[random.random() for _ in range(size)] for _ in range(size)]
    result = [[0.0 for _ in range(size)] for _ in range(size)]
    
    # 三重循环矩阵乘法
    for i in range(size):
        for j in range(size):
            for k in range(size):
                result[i][j] += a[i][k] * b[k][j]
    
    return result

def io_intensive_task(duration):
    """I/O密集型任务"""
    # 增加计算负载
    total = 0
    for i in range(1, 10000):
        total += math.log(i) * math.sin(i)
    
    # I/O等待
    time.sleep(duration * random.uniform(0.8, 1.2))
    return total

def run_test(task_func, warmup=None, repeats=None):
    """优化的测试运行函数"""
    warmup = warmup or CONFIG['warmup_repeats']
    repeats = repeats or CONFIG['test_repeats']
    
    # 预热
    for _ in range(warmup):
        task_func()
    
    times = []
    for _ in range(repeats):
        start = time.perf_counter()
        task_func()
        end = time.perf_counter()
        times.append(end - start)
    
    if len(times) > 1:
        return statistics.mean(times), statistics.stdev(times)
    else:
        return times[0], 0.0

def test_fibonacci_performance():
    """斐波那契测试"""
    print("斐波那契计算性能测试...")
    
    def single_fib():
        results = []
        for _ in range(CONFIG['cpu']['fib_runs']):
            results.append(cpu_intensive_fib(CONFIG['cpu']['fib_size']))
        return results
    
    def multi_fib():
        with ThreadPoolExecutor(CONFIG['cpu']['workers']) as executor:
            return list(executor.map(
                cpu_intensive_fib,
                [CONFIG['cpu']['fib_size']] * CONFIG['cpu']['fib_runs']
            ))
    
    def multi_process_fib():
        with ProcessPoolExecutor(CONFIG['cpu']['workers']) as executor:
            return list(executor.map(
                cpu_intensive_fib,
                [CONFIG['cpu']['fib_size']] * CONFIG['cpu']['fib_runs']
            ))
    
    return {
        '单线程(斐波那契)': run_test(single_fib),
        '多线程(斐波那契)': run_test(multi_fib),
        '多进程(斐波那契)': run_test(multi_process_fib)
    }

def test_prime_performance():
    """素数计算测试"""
    print("素数计算性能测试...")
    
    def single_prime():
        results = []
        for _ in range(CONFIG['cpu']['prime_runs']):
            results.append(compute_primes(CONFIG['cpu']['prime_range']))
        return results
    
    def multi_prime():
        with ThreadPoolExecutor(CONFIG['cpu']['workers']) as executor:
            return list(executor.map(
                compute_primes,
                [CONFIG['cpu']['prime_range']] * CONFIG['cpu']['prime_runs']
            ))
    
    def multi_process_prime():
        with ProcessPoolExecutor(CONFIG['cpu']['workers']) as executor:
            return list(executor.map(
                compute_primes,
                [CONFIG['cpu']['prime_range']] * CONFIG['cpu']['prime_runs']
            ))
    
    return {
        '单线程(素数计算)': run_test(single_prime),
        '多线程(素数计算)': run_test(multi_prime),
        '多进程(素数计算)': run_test(multi_process_prime)
    }

def test_matrix_performance():
    """矩阵计算测试"""
    print("矩阵计算性能测试...")
    
    def single_matrix():
        results = []
        for _ in range(CONFIG['cpu']['matrix_runs']):
            results.append(matrix_multiply(CONFIG['cpu']['matrix_size']))
        return results
    
    def multi_matrix():
        with ThreadPoolExecutor(CONFIG['cpu']['workers']) as executor:
            return list(executor.map(
                matrix_multiply,
                [CONFIG['cpu']['matrix_size']] * CONFIG['cpu']['matrix_runs']
            ))
    
    def multi_process_matrix():
        with ProcessPoolExecutor(CONFIG['cpu']['workers']) as executor:
            return list(executor.map(
                matrix_multiply,
                [CONFIG['cpu']['matrix_size']] * CONFIG['cpu']['matrix_runs']
            ))
    
    return {
        '单线程(矩阵计算)': run_test(single_matrix),
        '多线程(矩阵计算)': run_test(multi_matrix),
        '多进程(矩阵计算)': run_test(multi_process_matrix)
    }

def test_io_performance():
    """I/O性能测试"""
    print("I/O性能测试...")
    
    def single_io():
        results = []
        for _ in range(CONFIG['io']['task_count']):
            results.append(io_intensive_task(CONFIG['io']['base_duration']))
        return results
    
    def multi_io():
        with ThreadPoolExecutor(CONFIG['io']['workers']) as executor:
            return list(executor.map(
                io_intensive_task,
                [CONFIG['io']['base_duration']] * CONFIG['io']['task_count']
            ))
    
    def multi_process_io():
        with ProcessPoolExecutor(CONFIG['io']['workers']) as executor:
            return list(executor.map(
                io_intensive_task,
                [CONFIG['io']['base_duration']] * CONFIG['io']['task_count']
            ))
    
    return {
        '单线程(I/O)': run_test(single_io),
        '多线程(I/O)': run_test(multi_io),
        '多进程(I/O)': run_test(multi_process_io)
    }

def print_detailed_results(results, title):
    """详细结果打印"""
    print(f"\n{title} 测试结果:")
    print("=" * 90)
    print(f"{'测试类型':<18} | {'平均时间(秒)':<12} | {'标准差':<12} | {'加速比':<10} | {'效率(%)':<10} | {'GIL影响':<10}")
    print("-" * 90)
    
    base_key = next((k for k in results if '单线程' in k), None)
    if base_key and results[base_key][0] > 0:
        base_time = results[base_key][0]
        
        for name, (avg, std) in results.items():
            if name == base_key:
                print(f"{name:<18} | {avg:<12.4f} | {std:<12.4f} | {'-':<10} | {'-':<10} | {'基准':<10}")
            elif avg > 0:
                speedup = base_time / avg
                efficiency = (speedup / CONFIG['cpu']['workers']) * 100
                gil_impact = "显著" if speedup < 1.2 else "较小"
                print(f"{name:<18} | {avg:<12.4f} | {std:<12.4f} | {speedup:<10.2f}x | {efficiency:<10.1f} | {gil_impact:<10}")

def analyze_comparison(py312_results, py314_results):
    """分析Python 3.12 vs 3.14的性能差异"""
    print("\n" + "=" * 90)
    print("Python 3.12 vs 3.14 性能对比分析")
    print("=" * 90)
    
    for test_type in ['斐波那契计算', '素数计算', '矩阵计算', 'I/O操作']:
        print(f"\n{test_type}:")
        print("-" * 50)
        
        # 这里需要你提供两个版本的具体测试数据
        # 我会在下一个版本中完善这个分析功能

def system_info():
    """系统信息"""
    import platform
    
    print("=" * 70)
    print("系统信息")
    print("=" * 70)
    print(f"操作系统: {platform.platform()}")
    print(f"处理器: {platform.processor()}")
    print(f"CPU核心数: {multiprocessing.cpu_count()}")
    print(f"Python版本: {sys.version.split()[0]}")
    print(f"Free Threaded支持: {'是' if hasattr(sys, 'is_free_threaded') and sys.is_free_threaded else '否'}")

def run_benchmark():
    """主测试函数"""
    system_info()
    
    # 运行所有测试
    fib_results = test_fibonacci_performance()
    prime_results = test_prime_performance()
    matrix_results = test_matrix_performance()
    io_results = test_io_performance()
    
    # 显示结果
    print_detailed_results(fib_results, "斐波那契计算")
    print_detailed_results(prime_results, "素数计算")
    print_detailed_results(matrix_results, "矩阵计算")
    print_detailed_results(io_results, "I/O操作")

if __name__ == "__main__":
    run_benchmark()
    print("\n测试完成!")

测试结果

Python3.12

======================================================================
系统信息
======================================================================
操作系统: Windows-11-10.0.26100-SP0
处理器: Intel64 Family 6 Model 186 Stepping 2, GenuineIntel
CPU核心数: 16
Python版本: 3.12.4
Free Threaded支持: 否
斐波那契计算性能测试...
素数计算性能测试...
矩阵计算性能测试...
I/O性能测试...

斐波那契计算 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(斐波那契)          | 9.2754       | 0.0162       | -          | -          | 基准
多线程(斐波那契)          | 10.9490      | 0.1418       | 0.85      x | 5.3        | 显著
多进程(斐波那契)          | 1.8798       | 0.0815       | 4.93      x | 30.8       | 较小

素数计算 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(素数计算)          | 22.5735      | 0.8367       | -          | -          | 基准
多线程(素数计算)          | 24.4017      | 0.2519       | 0.93      x | 5.8        | 显著
多进程(素数计算)          | 6.2877       | 2.9351       | 3.59      x | 22.4       | 较小

矩阵计算 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(矩阵计算)          | 15.0526      | 0.7845       | -          | -          | 基准
多线程(矩阵计算)          | 20.1084      | 0.9290       | 0.75      x | 4.7        | 显著
多进程(矩阵计算)          | 4.6684       | 2.6786       | 3.22      x | 20.2       | 较小

I/O操作 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(I/O)           | 1.2050       | 0.0166       | -          | -          | 基准
多线程(I/O)           | 0.1431       | 0.0102       | 8.42      x | 52.6       | 较小
多进程(I/O)           | 3.1059       | 0.0387       | 0.39      x | 2.4        | 显著

测试完成!

Python3.14t

======================================================================
系统信息
======================================================================
操作系统: Windows-11-10.0.26100-SP0
处理器: Intel64 Family 6 Model 186 Stepping 2, GenuineIntel
CPU核心数: 16
Python版本: 3.14.0
Free Threaded支持: 否
斐波那契计算性能测试...
素数计算性能测试...
矩阵计算性能测试...
I/O性能测试...

斐波那契计算 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(斐波那契)          | 9.7135       | 0.0881       | -          | -          | 基准
多线程(斐波那契)          | 1.8736       | 0.0241       | 5.18      x | 32.4       | 较小
多进程(斐波那契)          | 2.0165       | 0.0576       | 4.82      x | 30.1       | 较小

素数计算 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(素数计算)          | 19.5347      | 0.8062       | -          | -          | 基准
多线程(素数计算)          | 4.1509       | 0.1237       | 4.71      x | 29.4       | 较小
多进程(素数计算)          | 3.9353       | 0.4576       | 4.96      x | 31.0       | 较小

矩阵计算 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(矩阵计算)          | 23.4435      | 0.8085       | -          | -          | 基准
多线程(矩阵计算)          | 4.3176       | 0.0383       | 5.43      x | 33.9       | 较小
多进程(矩阵计算)          | 3.9503       | 0.2226       | 5.93      x | 37.1       | 较小

多线程(矩阵计算)          | 4.3176       | 0.0383       | 5.43      x | 33.9       | 较小
多线程(矩阵计算)          | 4.3176       | 0.0383       | 5.43      x | 33.9       | 较小
多进程(矩阵计算)          | 3.9503       | 0.2226       | 5.93      x | 37.1       | 较小

I/O操作 测试结果:
==========================================================================================
测试类型               | 平均时间(秒)      | 标准差          | 加速比        | 效率(%)      | GIL影响
------------------------------------------------------------------------------------------
单线程(I/O)           | 1.3403       | 0.0052       | -          | -          | 基准
多线程(I/O)           | 0.0402       | 0.0022       | 33.32     x | 208.2      | 较小
多进程(I/O)           | 0.8781       | 0.0145       | 1.53      x | 9.5        | 较小

测试完成!

Python 3.12和Python 3.14的性能进行对比分析:

1. 斐波那契计算性能对比

Python 3.12:
多线程加速比: 0.85x (比单线程更慢)
多进程加速比: 4.93x
Python 3.14:
多线程加速比: 5.18x (显著提升)
多进程加速比: 4.82x

分析: Python 3.14在多线程性能上有显著提升,几乎与多进程性能相当,表明GIL的影响在3.14中得到了优化。

2. 素数计算性能对比

Python 3.12:
多线程加速比: 0.93x
多进程加速比: 3.59x
Python 3.14:
多线程加速比: 4.71x
多进程加速比: 4.96x

分析: Python 3.14的多线程性能提升明显,与多进程性能接近,再次证实GIL优化效果。

3. 矩阵计算性能对比

Python 3.12:
多线程加速比: 0.75x
多进程加速比: 3.22x
Python 3.14:
多线程加速比: 5.43x
多进程加速比: 5.93x

分析: 矩阵计算中,3.14的多线程性能提升最为显著,甚至超过了3.12的多进程性能。

4. I/O操作性能对比

Python 3.12:
多线程加速比: 8.42x
多进程加速比: 0.39x
Python 3.14:
多线程加速比: 33.32x (惊人提升)
多进程加速比: 1.53x

分析: Python 3.14在I/O密集型任务上的多线程性能提升最为显著,达到了33倍加速。

综合结论

GIL优化: Python 3.14在多线程CPU密集型任务上的表现显著优于3.12,表明GIL的实现得到了重大改进。
性能提升幅度:
CPU密集型任务: 多线程性能提升5-7倍
I/O密集型任务: 多线程性能提升近4倍
多线程vs多进程:
在3.14中,多线程性能已接近多进程性能,减少了需要使用多进程的场景
版本选择建议:
对于CPU密集型应用: 推荐使用3.14,特别是多线程场景
对于I/O密集型应用: 强烈推荐使用3.14
注意事项:
3.14的多进程性能与3.12相当,没有显著提升
测试显示3.14的单线程性能略有下降(斐波那契从9.27s→9.71s),可能是优化多线程的代价

这些结果表明Python 3.14在多线程编程模型上取得了重大突破,使得开发者可以更简单地通过多线程而非多进程来获得性能提升。

读者评论

评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。

0/1500

暂无评论,欢迎抢沙发。