如何尝试使用try / except bad来衡量执行情况

问题描述 投票:0回答:1

对不起我的英语。我需要显示出在Python中正确使用try / except的内容。我尝试使用严格和错误的方式,并以错误的方式等待更多的时间执行,但我无法证明这一点。我是python的新手。我认为只有那些生成异常的行需要在try块中,我知道n = 1000000不会生成异常,而仅用于在相同条件下进行测试。问候。丹尼尔

from time import time
#**************************
#Right use, I suppose
#**************************
start1=time()
try:
    n=1000000
except:
     print('Error en el ingreso')  
while n>=0: #out try is more fast?
       n-=1 #out try is more fast?
end1=time()#end mark good time
good=end1-start1
print('Time right used: {}'.format(good))
#**************************
#Wrong use, I suppose
#**************************
start2=time()
try: 
    n=1000000
    while n>=0:#in try is more slow?
       n-=1    #in try is more slow?
except:
    print('Error en el ingreso')         
end2=time()
bad=end2-start2#end mark bad time
print('Time wrong used: {}'.format(bad))

if bad>=good:
    print('Bad use take more time')
else:
    print('Good use take more time')
python try-catch execution
1个回答
0
投票

一些注意事项:

  • time.time()返回“挂钟”时间。在对代码进行基准测试时,这是一个不好的指标。您要测量的是CPU完成代码所需的时间。为此,您可以使用timeit模块。
  • 基准测试时,尝试编写运行时间短的最小的代表性代码,以便您可以多次执行并取平均值(使用timeit。]]
  • 到示例:

from timeit import timeit

def loop_with_tryexcept():
    try:
        n = 10_000
        while n >= 0:
            n -= 1
    except:
        print("Error")

def loop_without_tryexcept():
    n = 10_000
    while n >= 0:
        n -= 1


"""
python -i test.py

>>> timeit('loop_with_tryexcept()', setup='from __main__ import loop_with_tryexcept', number=1000)
0.49678000000017164
>>> timeit('loop_without_tryexcept()', setup='from __main__ import loop_without_tryexcept', number=1000)
0.5228376000000026

# It seems a tiny bit faster. Or is it?


>>> timeit('loop_with_tryexcept()', setup='from __main__ import loop_with_tryexcept', number=1000)
0.4899204999999256
>>> timeit('loop_without_tryexcept()', setup='from __main__ import loop_without_tryexcept', number=1000)
0.4767956000000595

# Nope, it was just randomness introduced by the CPU.
"""

您可以看到,将代码包装在try / except块中时,速度没有差别。

© www.soinside.com 2019 - 2024. All rights reserved.