by andai · 2y ago · 0 comments
They claimed that the hash function was used constantly —e.g. 11 times in print("hello world")—because it's used to look up object properties.
Apparently the default implementation is not optimized for performance but for security, just in case the software is exposed to the web. None of my Python programs are, so assuming all this is true, I'd much prefer to have a "I'm offline, please run twice as fast!" flag (or env variable).
The problem is that because Python is such a ubiquitous language, CPython gets more attention than it deserves. People see it as an archetypical implementation of a scripting language. We get blogposts like this examining its inner workings, discussions about how its performance could be improved, comparisons of its speed vs. compiled languages, and tutorials on how to optimize code to run faster in it. I feel like all of this effort would be better spent on discussions about runtimes that actually try to be fast.
NumPy, SciPy, TensorFlow, PyTorch, JAX, Pandas, Pillow, lxml, cjson, PyCapnP, Tornado, fast-avro, etc. all get it right. They are wrappers around C (or in some cases: Fortran/assembly/CUDA) code, where the overflow of Python method dispatch is dwarfed by the hundreds of thousands of iterations of an inner loop that's in optimized, vectorized assembly. Django, Protobufs, and Avro get it wrong (often for portability or developer velocity sake), where they wrote the whole library in Python at the expense of performance.
I was briefly tempted to write an API-compatible reimplementation of Django with the core in C++ when I left Google, but by then Django (and server-side web programming) was already falling out of favor, and if you're just shipping JSON to a SPA you can use cjson with any number of fast wsgi or asgi gateways.
My other two main options were Tcl and Perl. Tcl was excellent at gluing, but worse at scaling, with no namespaces (then) and OO only as third-party add-ons.
Perl extensions were not so easy (better with Perl 5), and much as I enjoyed the language, handling complex data structures, was not for the faint-hearted.
Gluing pieces of C together is why we have NumPy, PyQt, pywin32, wxPython, and tens of thousands of other packages that work with C/C++/Fortran libraries.
Where is this single use case intent articulated, by whom, and what year was it? What is the use case?
Today, it seems that Python is pitched for almost everything, short of ethernet drivers.
I think the "Python is pitched for almost everything" in that sentence shows a misinterpretation of gp's phrasing of "use case".
The "use case" isn't about different subject matter domains as if it was a claim about using Python as a universal language for writing database kernels or AAA games.
Instead, the "use case" is about the 2-level 2-language architecture of (1) a high-level scripting language and (2) extension modules that can be written in low-level C and imported into the interpreter. That's the "glue language" + "C Language" to combine the strengths of each language approach. (In contrast, Julia took approach of designing a language that was "fast enough" to avoid the "2 languages issue".)
>Where is this single use case intent articulated, by whom, and what year was it? What is the use case?
The Python "ergonomics use case" (not "domains use case") was originated by Python's inventor Guido van Rossum from the beginning in 1991. A clone of the 1991 Python source code has Guido's commentary for importing C modules:
https://github.com/smontanaro/python-0.9.1
Modern frameworks and libraries like TensorFlow and Pytorch continue the same use case of "high-level script glue code calling low-level C code" that was there in 1991. You can't write a tight cpu loop in pure Python code to paint a 60fps video game. That's not Python's intended use case. That philosophy is why a library like Tensorflow only has Python code for users to "glue" together the neural network graph which then calls out to the C++ code for the expensive cpu loops of backpropagation, gradient descent, etc.
'Python is a programming language that lets you work more quickly and integrate your systems more effectively.'
I like Django. I need to process data on the server side and like to write that in python because it is more convenient than C. I also built my GUI in Django without knowing JavaScript. "just shipping JSON" seems like a different use case.
I have a piece of hardware (a laboratory hardware switch) that exposes a REST API for CRUD. I wanted to build a GUI that formats and summarizes information and offers convenient control. The data is small enough so that python can process it without becoming the bottleneck. I used Django ORM to model the data and django forms with htmx for the GUI. Authentication was easily added to Django.
The ORM part was a bit painful as Django forms expect a queryset and a queryset is not be the result of a raw sql query. There is a way to feed list of tuples into a choices argument but I decided against that , and instead dumbed down my query so I was able to write it as an django ORM language query.
https://stackoverflow.com/questions/17330158/django-how-to-u...
I feel like as an industry we should step back and take a serious look at front end frameworks from first principles. One aspect that's clear to me, is that we should make modifications to HTML to support HTMX like transactions.
PyPy is in many aspects to be rated as a research project that tried a novel approach to reduce the workload compared to the manhours poured into V8,etc. LuaJIT managed with less with a focused language and a really capable lead. (Also I wouldn't be surprised if the PyPy team has also had to make compromises to get some kind of compatibility)
It's pretty well established that "Mike Pall" is the pen name for an AI sent from the future for unknown reasons. It disappeared from our light cone due to a rift in causality, presumably because it succeeded in whatever changes it wanted to make in the future.
Of course, "good" and "bad" are relative. If you don't care about performance then there's nothing wrong with CPython.
I mean one doesn't need more than:
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
to see. They have that special handling, but they still don't want to let you out, because... IMO, they just want to be annoying.When a solution could be something like:
Note: exit() is needed in scripts. In this prompt Ctrl-D (i.e. EOF) can also be used.
Exiting.To compare with Javascript: if I remember, as it appeared, V8 JIT was orders of magnitude faster, compared to the interpreted code.
Compared to JS pre-and-after modern engines it's a tiny improvement.
At the same time, I also agree with your sentiment.
[1] https://github.com/faster-cpython/ideas/wiki/Workflow-for-3....
I find that hard to believe that's a performance bottleneck. String hashes are all cached, and names like "print" are interned.
For a 2x overall gain I would expect to see the hash function pop up easily in my profiling, but I haven't seen it in my own profiling which was looking for simple things like that.
When siphash was evaluated, quoting https://peps.python.org/pep-0456/#performance , "In general the PEP 456 code with SipHash24 is about as fast as the old code with FNV" and "The summarized total runtime of the benchmark is within 1% of the runtime of an unmodified Python 3.4 binary".
Since then they switched from siphash24 to the faster siphash13. https://github.com/python/cpython/pull/28752
> The default hashing algorithm is currently SipHash 1-3, though this is subject to change at any point in the future. While its performance is very competitive for medium sized keys, other hashing algorithms will outperform it for small keys such as integers as well as large keys such as long strings, though those algorithms will typically not protect against attacks such as HashDoS.
https://doc.rust-lang.org/std/collections/struct.HashMap.htm...
However, Rust also lets you pick or implement your own hash algorithm if you want to optimise for your usecase.
However, Python does not use it for integers;
>>> hash(10)
10
>>> hash(100)
100
>>> hash(2**61-2) == 2**61-2
True
>>> hash(2**61-1)
0For the commonly used hash tables with prime size that use modulo to turn the hash code into a slot index, an identity hash for integers is usually fine (unless many integers are multiples of the prime size).
But other hash tables use power-of-two size to replace the modulo operation with a faster bit-and operation. Now an identity hash for integers is much more problematic, e.g. if all integers are multiples of 1000, only 1/8th of the table slots can be used.
The latter kind of hash tables would like all bits in the hash value to be well-distributed; and this is typically not true of the underlying integers. So an additional mixing operation needs to be used. Whether that mixing happens in the hash function or in the hash table depends on the implementation (for some, it's even configurable, e.g. is_avalanching marker in ankerl::unordered_dense).
>>> {i for i in range(10000)}
Takes 0.005s
>>> {i * sys.hash_info.modulus for i in range(10000)}
Takes 0.76s
I’d use “thoroughly disproven” rather than “disputed”.
I’m sure the hash function can be changed, but as various comments noted:
- the benchmark was nonsensical
- cpython caches string hashes, and “symbols” are interned, so outside of dynamic attribute access from dynamically constructed strings each hash for attribute purposes or namespace lookup is computed once per process
- and finally (though probably not the biggest issue) xxhash is known for being mostly useful on larger sizes (>128 bytes, although you can find better hashes (city IIRC) up to 512 or so)
Much like Rust, CPython uses siphash as its default, it’s a pretty good all rounder though not the fastest. It actually used to use FNV before HashDOS.
CPython does suffer from the inability of users to configure hash functions since it’s an object property rather than a container property.
In Rust, the Hash trait is only used to feed data to a hasher such that the type can decide what should be hashed. The creation of the hasher is done by the collection, and thus provides better opportunities / flexibility in customising the hash function.
This is most effective for reducing startup time of short lived scripts, where the runtime is dominated by many thousands of trivial mallocs right at startup. But in general if you can establish a bound on memory, it will be faster to allocate it in one shot.
The repo states that even this dummy implementation:
> has a 60% faster startup as compared to base CPython, and in some test cases has marginally better runtime performance as well.
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHA...
The original issue: https://bugs.python.org/issue13703
The hashseed is a per-process value, it has basically no impact on performances.
If I know anything about programmers, it's that everyone would just use the "go faster" flag by default.