mapLast, mapFirst, and just general iterator questions

Chris Angelico rosuav at gmail.com
Mon Jun 20 17:01:59 EDT 2022


On Tue, 21 Jun 2022 at 06:16, Leo <usenet at gkbrk.com> wrote:
>
> On Wed, 15 Jun 2022 04:47:31 +1000, Chris Angelico wrote:
>
> > Don't bother with a main() function unless you actually need to be
> > able to use it as a function. Most of the time, it's simplest to
> > just have the code you want, right there in the file. :) Python
> > isn't C or Java, and code doesn't have to get wrapped up in
> > functions in order to exist.
>
> Actually a main() function in Python is pretty useful, because Python
> code on the top level executes a lot slower. I believe this is due to
> global variable lookups instead of local.
>
> Here is benchmark output from a small test.
>
> ```
> Benchmark 1: python3 test1.py
>   Time (mean ± σ):     662.0 ms ±  44.7 ms
>   Range (min … max):   569.4 ms … 754.1 ms
>
> Benchmark 2: python3 test2.py
>   Time (mean ± σ):     432.1 ms ±  14.4 ms
>   Range (min … max):   411.4 ms … 455.1 ms
>
> Summary
>   'python3 test2.py' ran
>     1.53 ± 0.12 times faster than 'python3 test1.py'
> ```
>
> Contents of test1.py:
>
> ```
> l1 = list(range(5_000_000))
> l2 = []
>
> while l1:
>     l2.append(l1.pop())
>
> print(len(l1), len(l2))
> ```
>
> Contents of test2.py:
>
> ```
> def main():
>     l1 = list(range(5_000_000))
>     l2 = []
>
>     while l1:
>         l2.append(l1.pop())
>
>     print(len(l1), len(l2))
> main()
> ```
>

To be quite honest, I have never once in my life had a time when the
execution time of a script is dominated by global variable lookups in
what would be the main function, AND it takes long enough to care
about it. Yes, technically it might be faster, but I've probably spent
more time reading your post than I'll ever save by putting stuff into
a function :)

Also, often at least some of those *need* to be global in order to be
useful, so you'd lose any advantage you gain.

ChrisA


More information about the Python-list mailing list