我应该使用“if”吗?或“尝试” (作为速度问题)? [英] Should I use "if" or "try" (as a matter of speed)?

查看:51
本文介绍了我应该使用“if”吗?或“尝试” (作为速度问题)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个话题有可能在我脸上爆炸,

但是我不能帮忙问。我从1.5.1开始就一直在使用Python,所以我不是你要称之为n00b的
。每当我和其他开发人员交谈时,我都尽职尽责地宣传善意,但是当我讨论执行的细节时,我总是会遇到一个好的问题。 />
模型(特别是例外情况)。


当我开始与一些老前辈谈话时,没有失败

(在ADA或Fortran中编写代码的人),我听到使用if的相同

参数是更好的而不是使用尝试。我认为

这个论点就像是,当你设置''尝试''块时,你需要设置很多额外的机器而不是是必要的只是

执行一个简单的条件。


我想知道这对于Python有多么正确,其中例外是

这是执行模型的一个组成部分。在我看来,如果

我正在对一堆物品执行循环,并且我希望在大多数情况下保持一些

条件,然后是尝试块

将是有序的,因为我可以为每个项目消除一堆可能的昂贵的比较。但是,如果我只是尝试使用if(例如)一个getattr(例如),使用if可能是一个更便宜的方式来支付
go。


更便宜是什么意思?我基本上是在谈论设置和执行try块所需的数量

指令

而不是if块。


你能不能告诉我,我是否已经接近理解

这是正确的吗?

-

Steve Juranich

图森,亚利桑那州

美国

解决方案

老实说,我是对python来说相当新,但我最好的选择是创建

一些测试代码和时间。


我的镜头会要在你的平台上像这样测试它:


#!/ usr / bin / env python

导入日期时间,时间

t1 = datetime.datetime.now()

for i in [str(x)for x in range(100)]:

if int(i) ==我:

i + 1

t2 = datetime.datetime.now()

打印t2 - t1

为[in(x)for x in range(100)]中的i:

尝试:

int(i)+1

除外:

通过

t3 = datetime.datetime.now()

打印t3 - t2


对我来说(在AMD Sempron 2200+的Linux上的python 2.4.1上)它给出:

0:00:00.000637

0 :00:00.000823


Steve Juranich< sj ****** @ gmail.com>写道:

当我开始与一些老人(在ADA或Fortran中编写代码的人)开始交谈时,我会听到同样的消息。 >使用if的论据是更好的而不是使用尝试。


嗯,你现在失败了。我以前在打卡上写Fortran,所以

我想这让我成了老朋友,我不同意这个说法。

我认为这个论点类似于当你设置''尝试''块时,你必须设置很多额外的机器而不是必要的
只是执行一个简单的条件。 "


这听起来像是一种非常C ++的态度,其中效率值得珍惜

高于其他所有,并且异常处理相对较重的比较

到一个简单的条件。

我的意思是更便宜?我基本上是在谈论设置和执行try块所需的指令数量
而不是if块。




不要担心这样的废话,直到整个申请完成并且

它的运行速度不够快,而且你已经用尽所有努力来识别

可以进行的算法改进,以及细致的性能

测量结果表明使用try块是个问题。


例外情况更好而不是返回错误代码有几个原因:


1)他们不能被意外地默默忽略。如果你没有发现

异常,它会一直冒出来,直到有什么东西能够捕获它,或者什么都没有,并且你的程序会因堆栈跟踪而死亡。如果你愿意,你可以忽略它们,但是你必须明确地写一些代码才能做到这一点。


2)它将正常的控制流与错误处理。在

很多情况下,这使得理解程序逻辑变得更容易。


3)在某些情况下,它们可以导致更快的代码。一个典型的例子是

使用字典计算项目的出现:


count = {}

用于键入任何内容:

尝试:

count [key] + = 1

除了KeyError:

count [key] = 1


比较


count = {}

用于钥匙的任何:

if count.hasKey(key):

count [key] + = 1

else:

count [key] = 1


如果大多数密钥已经在字典中,处理

偶然异常将比为每个密钥调用hasKey()更快。


I know that this topic has the potential for blowing up in my face,
but I can''t help asking. I''ve been using Python since 1.5.1, so I''m
not what you''d call a "n00b". I dutifully evangelize on the goodness
of Python whenever I talk with fellow developers, but I always hit a
snag when it comes to discussing the finer points of the execution
model (specifically, exceptions).

Without fail, when I start talking with some of the "old-timers"
(people who have written code in ADA or Fortran), I hear the same
arguments that using "if" is "better" than using "try". I think that
the argument goes something like, "When you set up a ''try'' block, you
have to set up a lot of extra machinery than is necessary just
executing a simple conditional."

I was wondering how true this holds for Python, where exceptions are
such an integral part of the execution model. It seems to me, that if
I''m executing a loop over a bunch of items, and I expect some
condition to hold for a majority of the cases, then a "try" block
would be in order, since I could eliminate a bunch of potentially
costly comparisons for each item. But in cases where I''m only trying
a single getattr (for example), using "if" might be a cheaper way to
go.

What do I mean by "cheaper"? I''m basically talking about the number
of instructions that are necessary to set up and execute a try block
as opposed to an if block.

Could you please tell me if I''m even remotely close to understanding
this correctly?
--
Steve Juranich
Tucson, AZ
USA

解决方案

Honestly, I''m rather new to python, but my best bet would be to create
some test code and time it.


My shot would be to test it like this on your platform like this:

#!/usr/bin/env python
import datetime, time
t1 = datetime.datetime.now()
for i in [str(x) for x in range(100)]:
if int(i) == i:
i + 1
t2 = datetime.datetime.now()
print t2 - t1
for i in [str(x) for x in range(100)]:
try:
int(i) +1
except:
pass
t3 = datetime.datetime.now()
print t3 - t2

for me (on python 2.4.1 on Linux on a AMD Sempron 2200+) it gives:
0:00:00.000637
0:00:00.000823


Steve Juranich <sj******@gmail.com> wrote:

Without fail, when I start talking with some of the "old-timers"
(people who have written code in ADA or Fortran), I hear the same
arguments that using "if" is "better" than using "try".
Well, you''ve now got a failure. I used to write Fortran on punch cards, so
I guess that makes me an "old-timer", and I don''t agree with that argument.
I think that the argument goes something like, "When you set up a ''try''
block, you have to set up a lot of extra machinery than is necessary
just executing a simple conditional."
That sounds like a very C++ kind of attitude, where efficiency is prized
above all else, and exception handling is relatively heavy-weight compared
to a simple conditional.
What do I mean by "cheaper"? I''m basically talking about the number
of instructions that are necessary to set up and execute a try block
as opposed to an if block.



Don''t worry about crap like that until the whole application is done and
it''s not running fast enough, and you''ve exhausted all efforts to identify
algorithmic improvements that could be made, and careful performance
measurements have shown that the use of try blocks is the problem.

Exceptions are better than returning an error code for several reasons:

1) They cannot be silently ignored by accident. If you don''t catch an
exception, it bubbles up until something does catch it, or nothing does and
your program dies with a stack trace. You can ignore them if you want, but
you have to explicitly write some code to do that.

2) It separates the normal flow of control from the error processing. In
many cases, this makes it easier to understand the program logic.

3) In some cases, they can lead to faster code. A classic example is
counting occurances of items using a dictionary:

count = {}
for key in whatever:
try:
count[key] += 1
except KeyError:
count[key] = 1

compared to

count = {}
for key in whatever:
if count.hasKey(key):
count[key] += 1
else:
count[key] = 1

if most keys are going to already be in the dictionary, handling the
occasional exception will be faster than calling hasKey() for every one.


这篇关于我应该使用“if”吗?或“尝试” (作为速度问题)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆