Python repeating arithmetic

From a purely official point of view, as a rule, is it best to assign the result of a repeated arithmetic operation to a variable and use this variable throughout the code? Or Python has some internal way of caching the result and using it whenever it encounters a repeating statement.

For example, this is more efficient:

a = 50 b = a*12-1 c = a*b print c #some code print c*100 + 10 #some code print c/100 + 20 #etc 

Than this:

 print 50*(50*12-1) #some code print 50*(50*12-1) * 100 + 10 #some code print 50*(50*12-1) / 100 + 20 #etc 
+4
source share
3 answers

I seem to like very little speed:

 > python -m timeit 'a = 50; b = a*12-1; c = a*b; c; c*100+10; c/100+20;' 1000000 loops, best of 3: 0.27 usec per loop > python -m timeit '50*(50*12-1); 50*(50*12-1) * 100 + 10; 50*(50*12-1) / 100 + 20' 1000000 loops, best of 3: 0.218 usec per loop 

The assignment is slightly slower than the constant recount, but as korylprince says in the comments, the assignment will make it easier to read the code.

edit: I think this is what gnibbler had in mind in the comments, but it is slower:

 > python -m timeit 'def x(): a = 50; b = a*12-1; c = a*b; c; c*100+10; c/100+20;' 'x()' 1000000 loops, best of 3: 0.428 usec per loop 

edit2: This is really what gnibbler meant in the comments, and the difference is still careless. Comments about using a more readable file are saved:

 > python -m timeit -s 'def x(): a = 50; b = a*12-1; c = a*b; c; c*100+10; c/100+20;' 'x()' 1000000 loops, best of 3: 0.367 usec per loop > python -m timeit -s 'def x(): 50*(50*12-1); 50*(50*12-1) * 100 + 10; 50*(50*12-1) / 100 + 20' 'x()' 1000000 loops, best of 3: 0.278 usec per loop 
+2
source

I don't know any Python implementation that caches intermediate results. Binding a local variable is pretty cheap, so after a few calculations it will come out faster.

In special cases where only constants are used, the eye optimizer can reduce them to constants

eg.

 $ python3.3 Python 3.3.0 (default, Sep 29 2012, 17:17:45) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def x(): ... 50*(50*12-1) ... 50*(50*12-1) * 100 + 10 ... 50*(50*12-1) / 100 + 20 ... >>> dis.dis(x) 2 0 LOAD_CONST 9 (29950) 3 POP_TOP 3 4 LOAD_CONST 14 (2995010) 7 POP_TOP 4 8 LOAD_CONST 19 (319.5) 11 POP_TOP 12 LOAD_CONST 0 (None) 15 RETURN_VALUE 

If in doubt, prefer a readable version. Micro-optimization if you really need these extra microseconds

+7
source

A literal will be faster because it does not need to refer to anything. There is no preprocessing in Python, so you cannot make #define, as in C.

0
source

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


All Articles