Python and the need for speed

Marko Rauhamaa marko at pacujo.net
Wed Apr 12 06:11:00 EDT 2017


bart4858 at gmail.com:

> On Wednesday, 12 April 2017 07:48:57 UTC+1, Steven D'Aprano  wrote:
>> Here's another example:
>> 
>>     answer = 0
>>     for i in range(10):
>>         answer += 1
>> 
>> instead of 
>> 
>>     answer = 10
>> 
>> So... how exactly does the compiler prohibit stupid code?
>
> Actually, an optimising C compiler (not one of mine!) probably could
> reduce that to answer=10.

One of the reasons C compilers need to address "stupid" code like that
is that it may arise from macros or from generated code. Maybe the
statement "answer += 1" is "answer = answer * 1.01 + 0.0001" in some
other (compile-time) circumstances.

A similar situation can hit Python as well through a (virtual) method
call, a dynamic function call or a conditional import, for example.


Marko



More information about the Python-list mailing list