Python if still micro-optimization

In thinking about code optimization, I was wondering what was more expensive in python:

if x:
    d = 1
else:
    d = 2

or

d = 2
if x:
    d = 1

Any thoughts? I like the reduction in the number of rows in the second, but wondered if remapping was more expensive than switching conditions.

+3
source share
4 answers

Do not meditate, do not be surprised, measure - from timeit the command line shell (certainly the best, easiest way to use it!). Python 2.5.4 on Mac OSX 10.5 on a laptop ...:

$ python -mtimeit -s'x=0' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0748 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0685 usec per loop
$ python -mtimeit -s'x=0' 'd=2' 'if x: d=1'
10000000 loops, best of 3: 0.0734 usec per loop
$ python -mtimeit -s'x=1' 'd=2' 'if x: d=1'
10000000 loops, best of 3: 0.101 usec per loop

: "just-if" 1,4 , x , 40,2 , x , "if/else"; - , x 30 , true . :

$ python -mtimeit -s'x=0' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0736 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.076 usec per loop

... if if .

, , , , " " . , vs expression if/else "x is true", :

$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.076 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0749 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0742 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0749 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0745 usec per loop

, ( ) 74,2 76,0 - , . :

$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0688 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0681 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0687 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0679 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0692 usec per loop

, ( ) 67,9 69,2 ; x 4,8 8,1 ( 6,3 6,8 , min/min max/max min/max max/max, , , ).

, , , , , .

+20

, , , , :

d = 1 if x else 2
+5

, , , , x , x .

: python , , , , , , .

+2

, ( ).

if... else , / .

The assignment construct may matter more if (d == 2) is the usual value and your if tests are for the unusual case. This design becomes less clear if your job moves away from if.

In this simple example, this is not a big deal. For more complex code, I would almost always optimize for readability, even at the cost of several processor cycles.

+1
source

Source: https://habr.com/ru/post/1726561/


All Articles