以下是我的脚本:
for a in range(-100, 101):
for b in range(-100, 101):
for c in range(-100, 101):
for d in range(-100, 101):
if abs(2**a*3**b*5**c*7**d-0.3048) <= 10**(-6):
print('a=',a, ', b=', b, ', c=', c,', d=', d,', the number=', 2**a*3**b*5**c*7**d, ', error=', abs(2**a*3**b*5**c*7**d-.3048))
字符串
在python中执行上面的脚本花了27分15秒。我知道它经历了201^4次表达式计算,但我需要更快地运行这些计算(因为我想尝试range(-200,201)
等等)。
我想知道是否有可能使上面的代码执行得更快。我认为使用numpy
数组会有所帮助,但不确定如何应用它,以及它是否真的有效。
2条答案
按热度按时间1szpjjfi1#
对于这些类型的计算,您可以尝试
numba
JIT:字符串
在我的机器(AMD 5700 X)上运行这段代码需要大约57秒(包括编译步骤)。相比之下,如果没有
@njit
(只是普通的Python),这只需要4分钟。型
看看你的代码,你可以使用
parallel range
(prange
)来进一步加快速度:型
在我的8 C/16 T机器上只需~2.7秒。
@EDIT:添加了存储中间结果。谢谢@yotheguitou
puruo6ea2#
几分钟后就开始了。
主要的速度改进只是预先计算所有的权力。我怀疑itertools实际上给了我任何东西。
你可能不是故意在一个位置使用.3048,在打印消息中使用3.048。我把两者都改成了.3048。也许你是指另一个。
字符串