5

I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible.

I have an if condition to test the divisor value in order to avoid the div by zero, but I am wondering that there is a performance impact that evaluating this if will have for each run in subsequent loops, especially since I know it's of no use anymore.

How should this be coded? in Python?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
greye
  • 8,921
  • 12
  • 41
  • 46
  • 3
    If you have to wonder if there is a performance impact, then most likely there is no performance impact. Don't waste your time anticipating performance problems that you haven't seen and measured yourself in the wild. – Tadeusz A. Kadłubowski Mar 26 '10 at 09:24

3 Answers3

9

Don't worry. An if (a != 0) is cheap.

The alternative (if you really want one) could be to split the loop into two, and exit the first one once the divisor gets its value. But that sounds like it would make the code unnecessarily complex (difficult to read).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    +1: there are possible options, but all of them would make the code less readable. I would consider switching to them only after a profiler indicated that loop as one of the main hit on global performance. – rob Mar 26 '10 at 07:07
6

I would wrap your call in try/except blocks. They are very cheap in python, and cost about as much as a pass statement if an exception isn't thrown. Python is designed so that you should make your calls and parse any errors instead of always asking permission.

Example code:

def print_divide(x,y):
    try:
        print x/y
    except ZeroDivisionError:
        pass
Kyle
  • 443
  • 3
  • 11
  • +1: Using the try:except mechanism means you aren't saddled with an if evaluation for every iteration though the loop after the initial 10 or so where the divisor is 0. –  Mar 26 '10 at 07:18
  • 3
    I think exceptions should be reserved for unexpected cases. Running into a ZeroDivisionError open-eyed when you know that the divisor will be 0 in the first couple of iterations, seems weird. Also, is a try/except really cheaper than a simple if? – Thilo Mar 26 '10 at 08:43
  • 1
    Re: "try/except really cheaper than a simple if". Apparently it is: http://stackoverflow.com/questions/2522005/cost-of-exception-handlers-in-python – Thilo Mar 26 '10 at 09:17
1

I'm with Thilo: I think it should be pretty cheap.

If you really care, you should time the code and find out whether the slight overhead is unacceptable. I suspect not.

George V. Reilly
  • 15,885
  • 7
  • 43
  • 38