Python伪随机数生成器运行耗时近1小时,如何优化实现数秒出结果?
Python循环性能优化方案
你当前代码的性能瓶颈是执行了2^30次(约10.7亿次)Python级别的循环操作,Python原生单循环执行效率极低,自然要消耗近1小时。优化可以直接从算法逻辑层面降维,完全不需要遍历循环:
核心优化逻辑
你代码的循环本质是计算32位无符号整数下的结果:初始值 * 乘数 ^ 循环次数 mod 2^32,等价于直接使用模幂运算一步得到结果,不需要逐次循环计算。
优化后代码
from time import process_time MOD = 2 ** 32 i0 = 987654321 a = 663608941 r = 2 ** 30 t1_start = process_time() # 直接用内置模幂函数计算,底层为C实现,效率极高 result = (i0 * pow(a, r, MOD)) % MOD t1_stop = process_time() print("\nLoop stopped at the element:", result, ".\n") print("Is this the last element of the series? 1 for YES other numbers for NO", result / 987654321, ".\n") print("The CPU time needed in order to take to go throught the whole sequence is", t1_stop - t1_start, "seconds.\n")
优化效果
- 运算时间从近1小时降低到毫秒级,完全可以在1秒内得到结果
- 计算结果和原循环遍历得到的结果完全一致,没有精度损失
内容的提问来源于stack exchange,提问作者J.Snowden
相关产品推荐
相关产品推荐

