修改一行,使pypy执行脚本提速几十倍

张开发
2026/4/20 16:52:24 15 分钟阅读

分享文章

修改一行,使pypy执行脚本提速几十倍
如下python脚本def calculate_A_correct(max_f): #print(max_f) # 创建足够大的数组 A [[0] * (max_f 2) for _ in range(max_f 2)] # 初始化 A[0][0] 0 A[0][1] 1 # 第一行m0a(n) a(n-1) 3*a(n-2) for n in range(2, max_f 1): A[0][n] A[0][n-1] 3 * A[0][n-2] # 计算其他行 for m in range(1, max_f 1): # 第0列用递推公式 A[m][0] A[m-1][1] A[m-1][0] A[m][0] A[m-1][1] A[m-1][0] # 其他列用递推公式 A[m][n] 2*A[m][n-1] A[m-1][n-1] for n in range(1, max_f 1): A[m][n] 2 * A[m][n-1] A[m-1][n-1] #A[m][n] A[m][n]%M return A def compute_S(k): # 生成斐波那契数 fib [0, 1] for i in range(2, k 1): fib.append(fib[-1] fib[-2]) max_f fib[k] # 调用正确的A函数计算数组 A calculate_A_correct(max_f) # 计算 S(k) total 0 for i in range(2, k 1): for j in range(2, k 1): m, n fib[i], fib[j] total A[m][n] total total%M return total M1123581313 # 测试 print(fS(3) {compute_S(3)}) print(fS(4) {compute_S(4)}) print(fS(5) {compute_S(5)}) print(fS(6) {compute_S(6)}) print(fS(20) {compute_S(20)%M})在pypy上执行比python更慢大约慢50%。time python3 940c.py S(3) 30 S(4) 276 S(5) 10396 S(6) 3544792 S(18) 536088899 real 0m4.463s user 0m3.650s sys 0m0.783s time pypy3/bin//pypy 940c.py Warning: cannot find your CPU L2 L3 cache size in /sys/devices/system/cpu/cpuX/cache S(3) 30 S(4) 276 S(5) 10396 S(6) 3544792 S(18) 536088899 real 0m6.070s user 0m5.151s sys 0m0.870s如果把# A[m][n] A[m][n]%M语句前面的注释符号去掉time python3 940c.py S(3) 30 S(4) 276 S(5) 10396 S(6) 3544792 S(18) 536088899 real 0m2.268s user 0m2.131s sys 0m0.119s time pypy3/bin//pypy 940c.py Warning: cannot find your CPU L2 L3 cache size in /sys/devices/system/cpu/cpuX/cache S(3) 30 S(4) 276 S(5) 10396 S(6) 3544792 S(18) 536088899 real 0m0.207s user 0m0.158s sys 0m0.047spython执行提速了2倍而pypy提速了30倍。

更多文章