Là thử ngoại trừ nhanh hơn nếu python?

Steven D'Aprano steve tại pearwood. thông tin
Thứ hai Tháng một 10 01. 22. 33 CET 2011
Karim wrote:
> 
> Hello all,
> 
> I am using more and more try except statement. But I discussed with a 
> very experienced C++ programmer.
> And he told me that at least in C++ using too many try -catch statements 
> are making the code slower. And it should
> does the same for python [C implementation]. 

He is right with the first part, wrong with the second. Python's 
exceptions are not the same as C++ or Java exceptions.

Setting up a try...except block is *very* fast, unlike C++ and Java, 
where it is slow. In Python, this code:

try:
     1+1  # cannot fail
except ValueError:
     pass


is just as fast as:


pass  # null op, does nothing
1+1  # cannot fail


So there is no speed penalty for setting up a try...except block. If you 
have something that will nearly always succeed, you don't need to be 
concerned about using an exception handler.

However, *catching* the exception is more expensive. [Roughly ten times 
as expensive.] So you should avoid code that mostly fails.

Remember, also, that the alternative to try...except also has a cost 
which might not be cheap. You can do this:


try:
     something that might fail
except Failure:
     do alternative


or you can do this:

if something should succeed:
     do something
else:
     do alternative


But this if...else test is not free. Depending on how expensive the test 
is, and how often you take each branch, it might be more expensive to 
"look before you leap". Also, remember that many tests are disguised 
exceptions, such as the builtin "hasattr" function:

# pseudo-code
def hasattr[obj, name]:
     try:
         getattr[obj, name]
     except AttributeError:
         return False
     return True


So there is no speed advantage to calling:

if hasattr[obj, 'spam']:
     print[obj.spam]
else:
     print["no spam in object"]

over this:

try:
     print[obj.spam]
except AttributeError:
     print["no spam in object"]


The first may even be slower because it has to look up the attribute 
twice -- this is what I call a pessimation, something done in the name 
of speed which actually makes your code *slower*.

Catching exceptions are best in three circumstances:

- You only care about the speed of a successful operation. Failures can 
be slow. If your program prints an error message and then exits, who 
cares if it takes 3 milliseconds longer than necessary?

- Testing whether something will succeed is impossible, or expensive, or 
too hard to get right.

- Failures are rare. As a *very* rough rule of thumb, I say that if you 
expect a failure less than one time in ten, it is better to use 
try...except.


But mostly, don't worry about speed. If you are worried about 
*execution* speed, you shouldn't be using Python in the first place. 
Python is optimized for developer productivity, not execution speed. 
Write your code, and *if* it is too slow, then worry about finding the 
bottlenecks and optimizing them.

Some very important quotes about optimization in general:

“More computing sins are committed in the name of efficiency [without 
necessarily achieving it] than for any other single reason - including 
blind stupidity.” - W.A. Wulf

“We should forget about small efficiencies, say about 97% of the time: 
premature optimization is the root of all evil. Yet we should not pass 
up our opportunities in that critical 3%. A good programmer will not be 
lulled into complacency by such reasoning, he will be wise to look 
carefully at the critical code; but only after that code has been 
identified.” - Donald Knuth

“Bottlenecks occur in surprising places, so don't try to second guess 
and put in a speed hack until you have proven that's where the 
bottleneck is.” - Rob Pike

“The First Rule of Program Optimization: Don't do it. The Second Rule of 
Program Optimization [for experts only!]: Don't do it yet.” - Michael A. 
Jackson



-- 
Steven

Thông tin thêm về danh sách gửi thư Tutor

Khi xảy ra lỗi hoặc ngoại lệ như chúng ta gọi, Python thường sẽ dừng và tạo thông báo lỗi

Những ngoại lệ này có thể được xử lý bằng cách sử dụng câu lệnh try

Thí dụ

Khối try sẽ tạo ra một ngoại lệ, vì x không được xác định

thử.
  print[x]
ngoại trừ.
  print["Đã xảy ra ngoại lệ"]

Tự mình thử »

Vì khối try phát sinh lỗi nên khối except sẽ được thực thi

Nếu không có khối thử, chương trình sẽ bị lỗi và gây ra lỗi

Thí dụ

Câu lệnh này sẽ gây ra lỗi, vì x không được xác định

Tự mình thử »

Nhiều ngoại lệ

Bạn có thể xác định bao nhiêu khối ngoại lệ tùy thích, e. g. nếu bạn muốn thực thi một khối mã đặc biệt cho một loại lỗi đặc biệt

Thí dụ

In một thông báo nếu khối thử tăng 5 và một thông báo khác cho các lỗi khác

thử.
  print[x]
ngoại trừ NameError.
  print["Biến x không được xác định"]
ngoại trừ.
  print["Đã xảy ra sự cố khác"]

Tự mình thử »

Khác

Bạn có thể sử dụng từ khóa else để xác định một khối mã sẽ được thực thi nếu không có lỗi nào được đưa ra

Thí dụ

Trong ví dụ này, khối try không tạo ra bất kỳ lỗi nào

thử.
  print["Xin chào"]
ngoại trừ.
  print["Đã xảy ra sự cố"]
else.
  print["Không có gì sai"]

Tự mình thử »

Cuối cùng

Khối finally, nếu được chỉ định, sẽ được thực thi bất kể khối thử có gây ra lỗi hay không

Câu lệnh IF có nhanh hơn try không

Sẽ nhanh hơn nếu ngoại lệ thực sự là ngoại lệ . Nếu kết quả là Không quá 50% thời gian, thì sử dụng if có lẽ tốt hơn. Vì vậy, trong khi câu lệnh if luôn khiến bạn phải trả giá, thì việc thiết lập khối try/ngoại trừ gần như miễn phí. Nhưng khi Exception thực sự xảy ra thì chi phí còn cao hơn nhiều.

Python có thử không

Nhược điểm của Xử lý ngoại lệ Python . Dưới đây là ví dụ sử dụng module timeit của Python để kiểm tra thời gian thực hiện của 2 câu lệnh khác nhau. programs that make use try-except blocks to handle exceptions will run slightly slower, and the size of your code will increase. Below is an example where the timeit module of Python is being used to check the execution time of 2 different statements.

Có nên sử dụng try không

Lý do sử dụng thử/ngoại trừ là khi bạn có một khối mã để thực thi, khối mã này đôi khi sẽ chạy chính xác và đôi khi không , tùy thuộc vào .

Thử bắt có chậm hơn nếu không?

phương pháp bắt chậm hơn nếu . khác. Câu lệnh if nhanh hơn khoảng 50 giây. Hãy để tôi giải thích cho bạn. Trước hết đó không phải là ý kiến ​​cá nhân trừu tượng mà là một thử nghiệm đã được kiểm chứng.

Chủ Đề