News for hackers. Stuff that matters.
Re:Why Python is Slow: Looking Under the Hood (2014) by ptero on Wednesday October 25, 2017 @08:12AM (#15549379)
However, as posters in other thread said, the number and availability of libraries makes functionality of those small programs exceed that of much larger ones written in C or a similar language.

If you have to write a large project from scratch in Python it will be slow, but Python has gone pretty far in the direction where for many large tasks 90% of the functionality will be obtainable through standard libraries. Doing the remaining 10% in basic Python often keeps it competitive at runtime with compiled languages but produce much simpler, shorter and easier to maintain code.

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Wednesday October 25, 2017 @08:29AM (#15549462)
Python has great libraries, but the claim that you can use them and have code that competes with compiled languages is flat out wrong. CPython is at least an order of magnitude slower than Java/Go/Haskell/etc and two orders slower than C/C++/Rust/etc. PyPy closes the gap a bit, but it's still noticeably slower than the aforementioned compiled languages.

Note to responders--HN won't let me respond to you, because "I'm posting too fast".

Re:Why Python is Slow: Looking Under the Hood (2014) by acdha on Wednesday October 25, 2017 @09:09AM (#15549748)
Those statements are too broad to be anything other than flamebait. Which specific code did you benchmark?

That’s not to say that CPython isn’t slower than a compiled language but in common usage the gaps usually end up being much smaller because most of us aren’t paid to run fib() and things like I/O dominate or code ends up being in the same C libraries (libjpeg, OpenSSL, etc.).

I’ve seen multiple cases where Python beat C/Go because the app used something like dictionaries which was heavily optimized C code in the standard library.

Again, compiled languages should usually win but the details matter, especially since most people don’t do the exact same work you do. Simply tossing around big numbers with no support contributes noise rather than insight to the conversation.

Re:Why Python is Slow: Looking Under the Hood (2014) by hasenj on Wednesday October 25, 2017 @10:41AM (#15550489)
> Which specific code did you benchmark?

I had a csv file with ~16k entries. Each entry has a lat, lon, name and id.

The task: given a (lat, lon) pair, list all entries within 5km.

The simplest straight forward solution is to iterate the list, measure the distance of each item to the given point, and add it to the return list if the distance is within the desired range.

No crazy optimization or anything.

The results were something roughly like this:

The D version runs in 2~4ms when compiled with optimizations turned on to the max, and about 6~8ms without optimizations (just default compiler settings).

The Go version runs in about 6~8ms. (The Go compiler has no option to produce optimized code).

The python version runs in about 50ms.

That's 10x slower than Go and 20x slower than D.

This is python 3. Using pypy shows absolutely no difference in performance.

Obviously the time to load the data from the csv file into a list is not counted in the above results.

> I’ve seen multiple cases where Python beat C/Go because the app used something like dictionaries which was heavily optimized C code in the standard library.

That's exactly backwards.

The Go and D versions use structs which are compact data structures that pack the data together. So the entire array fits in one contiguous block of memory.

Python has no concept of structs, so you have to deal with dictionaries.

In general, writing optimized code is not a good idea. You should almost always write the most plain and straight forward code.

Because fast languages are fast by default, there's no optimization required. The straight forward solution is fast enough.

If you are writing Python, your code will be slow by default. You will need to think about ways to optimize it if you want better performance.

Re:Why Python is Slow: Looking Under the Hood (2014) by hasenj on Wednesday October 25, 2017 @08:04PM (#15555343)
I cannot edit my previous comment but just now I revisited the code and noticed there was an import inside the function measuring the distance. One I moved the import out of the function, the execution time was cut by a bit more than half, to about 20ms.

The go version runs in about 3ms, not 6ms.

The D version runs in 2ms.

So overall the python version is 10x slower than native, not 20x slower.

Which is still kind of bad.

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Wednesday October 25, 2017 @11:38AM (#15551000)
Worth noting that Python's csv library is optimized C, and it handily beats Go's so this benchmark must be dominated by non-CSV parsing.
Re:Why Python is Slow: Looking Under the Hood (2014) by hasenj on Wednesday October 25, 2017 @12:29PM (#15551543)
The csv parsing is not part of the benchmark.

The only thing I measured is iterating the list and matching entries within range of the input coordinate.

Re:Why Python is Slow: Looking Under the Hood (2014) by maxerickson on Wednesday October 25, 2017 @10:45AM (#15550534)
People talk about numpy as a numerical library, another way to think of it is as an api for interacting with contiguous chunks of memory.
Re:Why Python is Slow: Looking Under the Hood (2014) by tychver on Wednesday October 25, 2017 @01:41PM (#15552219)
The whole Ruby VM only takes ~50ms to start, so that sounds a bit slow. I wrote a quick version in Ruby and it only takes 5ms: https://gist.github.com/jamatthews/d910a2b39c87a871264dd31d1...
Re:Why Python is Slow: Looking Under the Hood (2014) by hasenj on Wednesday October 25, 2017 @07:56PM (#15555318)
It's a bit more complicated. I'm measuring geographical distances so I'm using haversine

    from math import radians, cos, sin, asin, sqrt
    def distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
        # taken from: https://stackoverflow.com/a/4913653/35364
        # convert decimal degrees to radians
        lon1 = radians(lon1)
        lon2 = radians(lon2)
        lat1 = radians(lat1)
        lat2 = radians(lat2)
        # haversine formula
        dlon = lon2 - lon1
        dlat = lat2 - lat1
        a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
        c = 2 * asin(sqrt(a))
        r = 6371008 # Average radius of earth in meters
        return c * r
Re:Why Python is Slow: Looking Under the Hood (2014) by tychver on Saturday October 28, 2017 @09:04AM (#15575015)
Using Haversine distance increases it to only 13ms. I'm not sure why your Python implementation is so slow? In the real world, things like haversine are implemented as C extensions, so I wrote one for Ruby as a comparison and it runs in 3.8ms for 16k points. https://gist.github.com/jamatthews/d910a2b39c87a871264dd31d1...

The Ruby GIS libaries already have C implementations for haversine but I just wanted to show how easy it is to hook out to a C function for math heavy stuff.

Re:Why Python is Slow: Looking Under the Hood (2014) by hasenj on Wednesday November 01, 2017 @12:59AM (#15598879)
It was slow because at first I put the import inside the function. Moving it out improved the python performance to 20ms (as I mentioned in another comment).

The javascript version runs in 15ms.

> In the real world, things like haversine are implemented as C extensions

Having to write C-extensions is, well a point of friction, and adds complexity.

If you just used a native language to begin with, the simple straight forward code would work just fine.

Btw the source is here, and it also includes the csv file. https://bitbucket.org/hasenj/geodb/src

Re:Why Python is Slow: Looking Under the Hood (2014) by tychver on Wednesday November 01, 2017 @11:36AM (#15602235)
Yeah, that'll do it!

C extensions are a core part of Ruby. A big chunk of the std lib is implemented in C. You shouldn't be afraid of writing a tiny bit of C. Ruby and Python are scripting languages. They're literally designed for scripting another language.

The JIT for Ruby 3 is well underway, so in a bit it'll be a complete non-issue anyway.

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Wednesday October 25, 2017 @01:51PM (#15552328)
> Those statements are too broad to be anything other than flamebait. Which specific code did you benchmark?

> Simply tossing around big numbers with no support contributes noise rather than insight to the conversation.

I resent that you characterize my comment as "flamebait" for lacking supporting evidence for my claim, when I was merely responding to your unsupported claim that Python competes with compiled languages. I chose to be broad because (as you point out), the range varies considerably by application and the margin for error is high, so it would be misleading to be artificially precise. It's perfectly reasonable that you want supporting evidence, but it doesn't make my post "lower quality" than yours.

As for "what I benchmarked", my comment was based on a decade of experience with these languages, including translating many proprietary systems from one language to another (sometimes a faster->slower language and sometimes a slower->faster language depending on whether I was optimizing for performance or security or maintainability).

> That’s not to say that CPython isn’t slower than a compiled language but in common usage the gaps usually end up being much smaller because most of us aren’t paid to run fib() and things like I/O dominate or code ends up being in the same C libraries (libjpeg, OpenSSL, etc.).

> I’ve seen multiple cases where Python beat C/Go because the app used something like dictionaries which was heavily optimized C code in the standard library.

I don't dispute that there are cases where Python beats naive C/Go. In particular, Python's csv lib is optimized C code, and it beats Go's CSV parser handily. If all you're doing is parsing CSVs and not actually calling into Python, you should probably stick with Python. While it's true that many applications are I/O bound, my figure was based on CPU time--it wouldn't make sense to judge languages by applications that are inherently I/O bound (although Go's async-by-default is much nicer than Python's async API). Besides, many applications are not I/O bound.

Re:Why Python is Slow: Looking Under the Hood (2014) by acdha on Wednesday October 25, 2017 @06:11PM (#15554755)
> I resent that you characterize my comment as "flamebait" for lacking supporting evidence for my claim, when I was merely responding to your unsupported claim that Python competes with compiled languages.

My point was simply that while it's easy to sit around talking about microbenchmarks that's not helpful for most developers. I've seen this cycle repeat so many times over the last couple decades because we're culturally prone to focusing on very small things and ignoring the larger picture:

Most developers are not employed to make a single thing as fast as possible but instead have to ship new features on a regular basis, handle a wide range of inputs correctly, etc.

Most of the performance problems people notice are due to application logic rather than low-level language characteristics, and that tends to mean things like I/O (API calls, poor file access patterns, etc.) or inefficient memory access patterns rather than how fast a loop can be.

I've seen slow applications in compiled languages replaced with a dynamic language and a big performance win not because of the underlying language characteristics but because writing in a lower-level (C, C++, Go) or more convoluted (Java J2EE) environment took enough longer that the development team was struggling just to complete features and the {Perl,PHP,Python,JS} team had considerably more time to optimize the core design.

I've also seen developers in all of those create huge labyrinths which made it hard to reason about the code's performance characteristics, and so my main concern these days is far less caring about the language than the overall amount of complexity you're asking developers to reason about and the related questions about the project and staffing.

Given unlimited time and budget, yes, a compiled language will probably win but for most projects the better question is “what tools will allow me to meet my goals with acceptable performance?” and that's a very different question.

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Wednesday October 25, 2017 @08:15PM (#15555394)
> My point was simply that while it's easy to sit around talking about microbenchmarks that's not helpful for most developers.

To be clear, I never mentioned or implied microbenchmarks.

> Most developers are not employed to make a single thing as fast as possible but instead have to ship new features on a regular basis, handle a wide range of inputs correctly, etc.

I absolutely agree that performance is just factor among many, but the scope of this entire post is "performance". Most of your points seem to pertain to "the biggest performance problem I see is with poor engineering practices". This is definitely a problem, and you're right to prioritize addressing it over choosing a fast language. No language is going to fix stupid, although I will say that Go makes it less appealing to write stupid code, thanks to its restrictive type system. So once you've fixed your stupidity problem, the language-level problems will start to crop up. :)

And by the way, since you mentioned memory access patterns and I/O, I want to point out that these are also language-level concerns. Since everything in Python is a reference into a random location of heap, memory access performance is terrible. Go lets you specify whether something is a pointer or a value, which means you can specify which things are collocated. This is important for good cache performance. Regarding I/O, Python makes you choose between async for performance or sync and your process does no work until the I/O completes. Go lets you write normal synchronous code, and the runtime/scheduler make async calls under the hood so code which doesn't depend on the result of your I/O can execute while other code blocks.

> Given unlimited time and budget, yes, a compiled language will probably win but for most projects the better question is “what tools will allow me to meet my goals with acceptable performance?” and that's a very different question.

It is a very different question, but as new compiled languages improve on ergonomics without compromising performance and as new interpreted languages improve on performance without compromising ergonomics, the answer will increasingly become "not CPython" (Python is the fastest growing language in 2017, but that's largely due to a surge in data science popularity; however, since Python is popular with the data science community largely because of its libraries and not language features, other languages will catch up [and indeed are catching up] quickly).

Re:Why Python is Slow: Looking Under the Hood (2014) by igouy on Thursday October 26, 2017 @10:00AM (#15558838)
> To be clear, I never mentioned or implied microbenchmarks.

> As for "what I benchmarked", my comment was based on a decade of experience with these languages…

No doubt others have based their comments on their experience, which they trust more.

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Thursday October 26, 2017 @01:24PM (#15561027)
I don't disagree; the parent asked where I got my estimates from and I answered.
Re:Why Python is Slow: Looking Under the Hood (2014) by igouy on Thursday October 26, 2017 @09:51AM (#15558765)
> Python is the fastest growing language in 2017, but that's largely due to a surge in data science popularity…

How do you know - "that's largely due to"?

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Thursday October 26, 2017 @01:24PM (#15561042)
There were a lot of analyses that came out about this recently. I don't remember specific articles, but they floated around this and other fora. I think StackOverflow may have had one.
Re:Why Python is Slow: Looking Under the Hood (2014) by hyperpape on Wednesday October 25, 2017 @09:50AM (#15550078)
Unless you're using order of magnitude to mean 2x, it's not the case that Java/Go/Haskell are an order of magnitude slower than C/C++/Rust. You can see that on the benchmarks game, the techempower benchmarks, or this lovely paper on optimizing Haskell and C: http://www.leafpetersen.com/leaf/publications/ifl2013/haskel....
Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Wednesday October 25, 2017 @11:32AM (#15550947)
I agree that the average is probably around 2X, but the variance and margin for error are pretty large, so I approximated. I didn't mean to imply that there was exactly a tenfold difference.
Re:Why Python is Slow: Looking Under the Hood (2014) by whyever on Wednesday October 25, 2017 @10:38AM (#15550468)
> Unless you're using order of magnitude to mean 2x, it's not the case that Java/Go/Haskell are an order of magnitude slower than C/C++/Rust.

It depends, in some benchmarks they are 10 times slower.

Re:Why Python is Slow: Looking Under the Hood (2014) by hyperpape on Wednesday October 25, 2017 @11:41AM (#15551029)
And you can construct cases where the JVM is infinitely faster than C/C++/Rust, because the JIT optimizes through a virtual call and detects dead code.

Should we say that "it depends, in some cases, Java is infinitely faster than C/C++/Rust"? Not unless we want to deliberately obscure the issue (or we want to warn someone about strange results). Benchmarks are about finding representative results across a variety of tasks.

If you think there are good benchmarks that show these languages are 10x slower in realistic cases, then you should share them, rather than just asserting that they're out there.

Re:Why Python is Slow: Looking Under the Hood (2014) by whyever on Wednesday October 25, 2017 @03:03PM (#15553114)
> Benchmarks are about finding representative results across a variety of tasks.

> And you can construct cases where the JVM is infinitely faster than C/C++/Rust, because the JIT optimizes through a virtual call and detects dead code.

How would that be a "representative result across a variety of tasks" according to your own definition of a benchmark? What do you mean by "across a variety of tasks"? That sounds like taking the average of some metric for different benchmarks, I'm not sure that is a good idea. I think it makes more sense to benchmark your specific use case, which is what I meant by "it depends".

> If you think there are good benchmarks that show these languages are 10x slower in realistic cases, then you should share them, rather than just asserting that they're out there.

I never said anything about "realistic" and "good", but they are really not unthinkably hard to find: http://benchmarksgame.alioth.debian.org/u64q/binarytrees.htm...

Re:Why Python is Slow: Looking Under the Hood (2014) by weberc2 on Wednesday October 25, 2017 @01:36PM (#15552162)
This is kind of my point; the variance and error margin are pretty wide. Specifying "2x" implies a precision I can't vouch for, so I settled for "an order of magnitude" as the general ballpark. If the 2x figure is important to you, I'm happy to make that concession.
Re:Why Python is Slow: Looking Under the Hood (2014) by hyperpape on Wednesday October 25, 2017 @01:48PM (#15552296)
I get the concern, but I'd say "a few times slower", which suggests 2x/3x/4x, not "an order of magnitude", which suggests something like 8x or 20x or whatever.
Re:Why Python is Slow: Looking Under the Hood (2014) by Can_Not on Wednesday October 25, 2017 @05:21PM (#15554391)
Orders of magnitude actually suggest the data would be best measured in exponents such as 10^3, 10^4, 10^5, etc because of it's range and distribution.
Re:Why Python is Slow: Looking Under the Hood (2014) by ptero on Wednesday October 25, 2017 @09:13AM (#15549772)
Can you provide some pointers / examples? This is an honest question -- I am not an expert on bare computation speed, but this (two orders of magnitude vs C++) has not been my experience.
Re:Why Python is Slow: Looking Under the Hood (2014) by igouy on Wednesday October 25, 2017 @02:57PM (#15553063)
A broad range -- Python programs are "as-fast-as-C" when they are C :-)

http://benchmarksgame.alioth.debian.org/u64q/compare.php?lan...

Re:Why Python is Slow: Looking Under the Hood (2014) by whyever on Wednesday October 25, 2017 @10:41AM (#15550490)