r/programming • • Aug 16 '18

7 Habits to Improve The Performance of Python Programs

https://www.tutorialdocs.com/article/7-habits-to-improve-python-programs.html
1 Upvotes

12 comments sorted by

10

u/kankyo Aug 16 '18

The first point is terrible advice. No way does this improve readability!

The actual advice to have faster Python is simple:

Profile and optimize algorithms and when that’s done don’t micro optimize but switch to cython or something.

1

u/crescentroon Aug 17 '18

The first point is terrible advice. No way does this improve readability!

True - but it's a significant performance improvement in older python interpreters, which is the point of the article.

don’t micro optimize but switch to cython or something

Compatibility...

Obviously python would not be a first choice for performance, but this appropriate for existing systems in which you can't afford to re-write from scratch. Or you're domain experts and not software engineers, and your primary expertise isn't programming, yet you need to write code (scientists, etc). "We" often forget in this sub how popular python is with data scientists.

1

u/kankyo Aug 18 '18

Cython is far from “rewriting from scratch”.

12

u/minusmakes Aug 16 '18

I love Python, that being said, I feel bad for people that need to optimize it for speed rather than using it as a prototyper or devops tool.

8

u/BeepBoopBike Aug 16 '18

This is my opinion in general. I recently prototyped a custom (non-generative, LR-inspired, table based) parser in python. It wasn't fast, but it let me try so many things very quickly. Using what I learned I wrote it 3 times and parsed a file with all versions: Python (original hacky version): 1 hour to parse the file Python: 30 minutes Python (using PyParsing): 40 minutes C++: 1 minute

I am 100% sure I could have made the python versions faster, but then I'm not doing anything fancy in the c++ version either, a few inline keywords and a couple of compiler flags. But there is absolutely no way in hell I could have written the c++ version without the flexibility of prototyping it in python first, and if I needed to parse small files the python version would have worked fine. It was only once I got to very large files that the speed became an issue. C++ is my "i'm writing this properly" language, Python is my "I wonder if this is possible/would work at all/good enough" language. Now I'm just considering speeding it up more by SIMDifying parts of it.

4

u/ironykarl Aug 16 '18

Not to take away from your story (you found one of the better use patterns for Python), but the runtime of your parser "should" have been a lot closer to the C++ parser. Like... very close.

How big a file were you parsing?

4

u/BeepBoopBike Aug 16 '18

haha I was expecting someone to comment on that. I was parsing log files which have a very 'loose' standard format, nothing you could reliably parse with regex in a sane way. I don't have the files around to check I just remember my test file being around 1 million lines of trace (slightly less iirc), although that doesn't tell you a lot in real terms.

In my comment I'm also generalising and skipping over a fair few details for brevity. I wasn't really trying to emphasise the outright performance differences. I get paid to write performant C++ all day and my python code is always prototyping or hacking something together so by default I write much more efficient C++ than I do Python equivalent and never need to worry about my Python being too slow, I profiled my python code at one point and found that it was bottlenecking on list operations surrounding tokenising the input strings and manipulating the output buffer during shift-reduce. There was probably a much faster way to manipulate the lists than I was doing, but hey prototyping! I'm again skipping over the fun details.

I mostly just wanted to tell a fun story about how I made a kinda-okay parser by using python to nail the concept instead of spending my time fighting the compiler when I just want to figure stuff out, I doubt I'd have even got the c++ version running first time if I'd not bothered with the python version first. The benchmarks I posted above were a large jump, but if I'd have had the same knowledge in python it would surely have been a much smaller difference. The main thing that surprised me was the performance I got from PyParsing, but again I probably missed something that would have made some great gains.

4

u/ironykarl Aug 16 '18

I mostly just wanted to tell a fun story about how I made a kinda-okay parser by using python to nail the concept instead of spending my time fighting the compiler when I just want to figure stuff out, I doubt I'd have even got the c++ version running first time if I'd not bothered with the python version first

Appreciate that

7

u/[deleted] Aug 16 '18

It’s really easy for a small shop to get something spun up serverside in python, and since its used with data so often it makes sense to need to optimize for traversing large files regularly

That being said, most of these optimizations are trivial and the article is worthless without benchmarks

-2

u/[deleted] Aug 16 '18

Thank you for sharing

0

u/[deleted] Aug 16 '18 edited Aug 16 '18

I don't get this:

#Each loop needs to re-execute len(a)
while i < len(a):
    statement
#Only execute len(a) once
m = len(a)
while i < m:
    statement

This is wrong because:

  • a whatever it is may be mutable and get mutated/changed during, in which case, the first is appropriate.

  • Is not the python way and is slower than the proper.

If you wish to do anything in an iterable, the best way is to use the proper tool for the job.

Alternatives:

for x in a:...
for i, x in enumerate(a):...
for i in range(len(a)):...
for i in sorted(a):...
for i in enumerate(sorted(a)):...

Or with functools:

from functools import reduce
err = reduce(lambda prev, nxt: prev or process(nxt),a,None)
if err != None:
     print(err)

#Or
issues = next((x for x in map(func,a) if x),None)
if err != None:
    print(err)

There are many ways to deal with iterables - which implement __len__(self) faster and better than C style loops.

Edit: It had been written down at a later point in the post but point remains, enumerate is better than C style loops.

0

u/ironykarl Aug 16 '18

I don't want to be purely negative, so... first the positive:

These are good things to think about, in the sense that knowing what your code does and how your interpreter works is necessary.

The negative: Most of these amount to pretty insignificant time saves while also making your code a but less readable.

I'm sure there are times in Python when your task is genuinely processor-bound. In those cases, obviously, having some knowledge of algorithms is gonna help a lot more than doing two fewer namespace lookups or iteration.

For I/O bound tasks (which has amounted to most of the Python programming I've done), choosing the right algorithm is also gonna be important, but sometimes so is just choosing the right standard library module/function. My Python's rusty, so no example here, but some depreciated standard library functions are going to do things way worse than newer equivalents.