Global VS Local Subroutines
BlindAnagram
blindanagram at nowhere.org
Thu Feb 10 12:33:59 EST 2022
On 10/02/2022 16:52, Rob Cliffe wrote:
>
>
> On 10/02/2022 12:13, BlindAnagram wrote:
>> Is there any difference in performance between these two program layouts:
>>
>> def a():
>> ...
>> def(b):
>> c = a(b)
>>
>> or
>>
>> def(b):
>> def a():
>> ...
>> c = a(b)
>>
>> I would appreciate any insights on which layout to choose in which
>> circumstances.
>>
> The way to answer questions about performance is not to guess (often
> difficult or impossible), but to measure. Profiling tools are available
> to see where a program spends how much of its time. But a simpler
> approach might be to try to run the guts of your program 1000 or 1000000
> times, and find how long it takes with each layout (not with a stopwatch
> 😁 but getting the program to record the start time, end time and the
> difference).
> That said, I will venture a guess (or at least, an observation):
> def a():
> ...
Thanks for the suggestion, Rob. I considered doing this but it would
take quite a bit of careful work to be sure of obtaining meaningful
results so I felt it better to ask the question here in case there was
an quick answer on performance before doing the hard work.
> is executable code. It creates the function `a` which did not exist
> before (or creates the new version if it did). This takes a certain
> amount of time. In your 2nd layout, this overhead occurs every time b()
> is called. So I would *guess* that this would be slower. Of course it
> depends on how many times b() is called and probably on lots of other
> things.
This is exactly what I felt too but I then wondered if the code was
recreated dynamically or was static with just a reference being created
on each invocation of the parent. The overhead in this case would be
negligible. But then I thought 'what about the context for the inner
function invocation' - maybe its not as simple as this! Oh dear, I need
to understand Python's internals.
At which point I asked the question!
Brian
More information about the Python-list
mailing list