python执行效率最高的是_python执行效率疑问

因为第二种算法是错的,多打印出了许多东西。break 之后合数还是被打印出来了。

PS: 利用 Python 3.2+ 的 functools.lru_cache,可以轻松实现更好的算法。

来,修正后的第二种算法为什么还是比较慢:

>>> time python2 a.py > /dev/null

python2 a.py > /dev/null 1.15s user 0.01s system 99% cpu 1.165 total

>>> time python2 b.py > /dev/null

python2 b.py > /dev/null 1.66s user 0.01s system 99% cpu 1.677 total

>>> time python2 c.py > /dev/null

python2 c.py > /dev/null 1.03s user 0.00s system 99% cpu 1.035 total

>>> time python2 a.py > /dev/null

python2 a.py > /dev/null 1.06s user 0.02s system 98% cpu 1.092 total

>>> time python2 b.py > /dev/null

python2 b.py > /dev/null 1.70s user 0.02s system 99% cpu 1.721 total

>>> time python2 c.py > /dev/null

python2 c.py > /dev/null 1.05s user 0.00s system 99% cpu 1.058 total

第三种算法如下:

def t():

for n in range(1, 200000):

if n <= 1:

continue

if n == 2:

print n

continue

if n % 2 == 0:

continue

i = 3

flag = True

while i * i <= n:

if n % i == 0:

flag = False

break

i += 2

if flag:

print n

t()

查找全局变量比查找局部变量慢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值