News for hackers. Stuff that matters.
Re:How Many Lines of C It Takes to Execute a and B in Python? by andai on Monday December 11, 2023 @04:51AM (#38599107)
A while back someone posted their patch to cpython where they replaced the hash function with a fast one and claimed this dramatically sped up the whole Python runtime.

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).

Re:How Many Lines of C It Takes to Execute a and B in Python? by Asraelite on Monday December 11, 2023 @06:56AM (#38599810)
This may be a somewhat uninformed opinion, but I think CPython is just straight up not particularly good software. There are a million and one optimizations that other major scripting runtimes (V8, LuaJIT, PyPy, Ruby YJit etc.) have had for years that CPython is lacking. This is by design though. CPython has never been focused on performance, that's why it's not even JIT. It optimizes for simplicity and easy interoperability with C.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Monday December 11, 2023 @07:20AM (#38599955)
Python rather happened to have a language design and C API design that doesn't allow a simple performant implementation. Even PyPy was not that fast compared to other JIT implementations, while its C API support was always subpar. It is easy to say that Python should trade them off for performance, but they are one of the key reasons for Python's success after all.
Re:How Many Lines of C It Takes to Execute a and B in Python? by whizzter on Monday December 11, 2023 @07:50AM (#38600192)
The semantic issues of making a performant Python language implementation are more or less exactly the same as for JS and Lua, optimizing Ruby seems to possibly have even more "magic" that needs patching but we've seen the Shopify team get cracking on that (it includes MaximeCB that did HiggsJS).

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)

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Monday December 11, 2023 @08:08AM (#38600309)
Unfortunately Python's innard is much more complicated than most expectations. You have named JS and Lua, but those languages never have "magic" methods---JS instead has prototypes and more recently proxies, while Lua has metatables. Ordinary objects aren't magic in this sense, and conversely magical objects are generally deliberate choices in those languages. But Python's magic `__dunder__` methods are everywhere including ordinary objects (and customized objects that look like ordinary objects, e.g. `list` subclasses). That alone complicates a lot of things.
Re:How Many Lines of C It Takes to Execute a and B in Python? by masklinn on Monday December 11, 2023 @08:49AM (#38600595)
It’s not entirely true that JS does not have magic methods. `valueOf` and `toString` can show up surprisingly deep into the resolution of operations, and recent JS has “well known symbols” to implement or override behaviour.

However it is true that this is much, much less extensive than it is in Python. As of 3.12, section 3.3 (“special method names”) of the data model documentation lists 107 entries (although some of them only apply to class protocols, and a handful are duplicates for async versions / context of sone operations).

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Monday December 11, 2023 @09:24AM (#38600879)
`valueOf` and `toString` are indeed fairly complex (and it's fun to consider when both are implemented ;-), but less of concern for tracing JIT engines because you can have efficient type-specialized implementations for most cases. Type specialization in Python is not that huge win...
Re:How Many Lines of C It Takes to Execute a and B in Python? by Sesse__ on Monday December 11, 2023 @12:11PM (#38602368)
Also, you have craziness like quite regular iteration being implemented using exceptions, which are not exactly trivial to optimize.
Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Monday December 11, 2023 @11:10PM (#38609342)
If you want to be return absolutely any value from an iterator, an exception is indeed a reasonable choice though. Python generators came in much later, unlike JS for example.
Re:How Many Lines of C It Takes to Execute a and B in Python? by Sesse__ on Wednesday December 13, 2023 @01:48AM (#38623552)
If that is indeed a requirement, you let your iterator have an .at_end() test instead of trying to shoehorn it into the return value. Or have something like C++'s std::optional or Rust's Option. Or a special EndOfIteration object that you cannot return from an iterator (is that really so bad?). Iteration is extremely common, and should thus be based on as simple primitives as possible if you want things to go fast.
Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Wednesday December 13, 2023 @05:18AM (#38625208)
I believe the original PEP [1] answers almost all questions. The only option not covered would be probably an "optional" type, but it is even easier to answer: any such type has to be heap-allocated in the Python memory model, so a mere iteration could've caused a lot of redundant memory allocations.

[1] https://peps.python.org/pep-0234/#rationale

Re:How Many Lines of C It Takes to Execute a and B in Python? by jerf on Monday December 11, 2023 @01:26PM (#38603397)
In the late 1990s and early 200xs, there were a lot of claims that there was no such thing as a "slow language", that all languages can be run as quickly as C if you just built a sufficiently smart compiler and/or runtime.

I haven't heard anyone make this claim in a while. The inability to speed up Python beyond a certain point despite a lot of clever approaches taken was probably a good chunk of the reason, the remainder being the wall that JS has hit despite the huge effort poured into it where it is still quite distinctly slower than C.

If I were designing a language to be slow, but not like stupidly slow just to qualify as an esolang, but where the slowness still contributed to things I could call "features" with a straight face, it would be hard to beat Python. I suppose I could try to mix in more of a TCL-style "everything is a string" and "accidentally" build some features on it that bust the string caching, but that's about all I can think of at this point.

Re:How Many Lines of C It Takes to Execute a and B in Python? by steveklabnik on Monday December 11, 2023 @03:33PM (#38605136)
I think this is really complicated. I do believe that it is important to separate language from implementation, and it is also true that different implementations can have different performance profiles. It is also true that the semantics of the language can effectively require specific implementation details that can affect performance either way. So there's always gonna be bounds to any particular languages' ability to be faster.

That is why the "as fast as C with the sufficiently smart compiler" never truly came to pass in a general sense, even if many languages that were slow to start have gotten way faster with better implementations.

Re:How Many Lines of C It Takes to Execute a and B in Python? by jerf on Tuesday December 12, 2023 @09:32AM (#38612594)
It certainly is complicated.

And I'd love to peer in to some alternate universe that has an optimal Python interpreter (can't say "the" optimal because it's really a complicated frontier rather than a single point) that runs on our hardware and see what it looks like. Maybe even on multiple points on that frontier.

What really is the limit? I struggle to imagine what a C-speed Python interpreter could even look like, but is there some conceivable program that runs it at, say, half the speed? What even is the limit? What techniques would such a program use that would surprise us and be new and perhaps useful other places?

Or are actually pretty close to that frontier now?

To be honest, given the way optimizations tend to work, the answer probably is that we are relatively close today. They tend to have diminishing returns.

But I don't know. Is there some execution model nobody's thought of, or that has been thought of but simply hasn't had the effort invested to make it pay off, that would make huge gains? I can't prove there isn't. (In fact it's not far off junior-level computer science to prove that you can't prove it.)

Re:How Many Lines of C It Takes to Execute a and B in Python? by steveklabnik on Tuesday December 12, 2023 @12:18PM (#38615206)
Yep, that'd be a lot of fun. I think back to the stuff that used to go on to optimize lua: http://lua-users.org/lists/lua-l/2011-02/msg00742.html

I also suspect that we are relatively close, and there are diminishing returns. I suspect that you would have to start the language design with this goal in mind, and then balance out performance concerns with certain features.

Re:How Many Lines of C It Takes to Execute a and B in Python? by slaymaker1907 on Monday December 11, 2023 @02:36PM (#38604406)
You could add in continuation support as well as unbounded stack size to make it even more difficult to implement efficiently. There are tricks these days for implementing continuations somewhat efficiently (and by somewhat, I mean that they're only 3-5x slower than explicit continuation passing with lambdas), but these tricks largely don't work in WASM without doing something extreme like completely ignoring the WASM stack and storing return addresses/current continuation on the WASM heap.

Unbounded stack size is similarly difficult for WASM because like before, you have to be very careful about using the WASM stack.

Even with C++, you basically need to drop down to intrinsics or assembly to make full use of SIMD.

Re:How Many Lines of C It Takes to Execute a and B in Python? by andai on Monday December 11, 2023 @02:35PM (#38604384)
Can someone explain what exactly it is about Python's design that makes it slow?

What changes would have to be made to speed it up? Obviously changing its core design now would break things, but my question is, can we can imagine an alternate universe Python that's as close as possible to our Python, except really fast? What would be different?

Re:How Many Lines of C It Takes to Execute a and B in Python? by AlotOfReading on Monday December 11, 2023 @03:29PM (#38605072)
It's the whole design. Every object creates allocation/gc overhead, bytecode dispatch is a major bottleneck, attribute lookup is expensive, objects are expensive, namespaces are expensive, etc.

You can change things internally (e.g. optimizing opcode parsing), fixed object layouts, restricting mutability, converting everything to predictable array accesses, but you'll likely just end up with something like Lua or Wren rather than Python, and people like Python specifically because of the ecosystem that's built up around that dynamicism over the years.

Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Tuesday December 12, 2023 @02:28AM (#38610678)
Smalltalk, Common Lisp and SELF are just as dynamic if not more, with a JIT.
Re:How Many Lines of C It Takes to Execute a and B in Python? by ngcc_hk on Thursday December 14, 2023 @05:50PM (#38648488)
That is a question in my mind throughout reading this discussion.

How about objective c vs swift from a dynamic at least type vs static one. Can swift be glue.

Re:How Many Lines of C It Takes to Execute a and B in Python? by whizzter on Wednesday December 13, 2023 @05:33PM (#38635142)
Iirc the slowness of CPython in all the above mentioned are artifacts of the implementation rather than the language itself.

The huge issue is that a big selling point for Python was the easy C-api integration providing lots of useful functionality via libraries now works as a chain that limits how many changes can be made (see any GIL-removal discussion).

The most sane way forward would be to mandate a conversion to a future-proof C-api (PyPy has already designed an initial one iirc that's tested and also has CPython support) that packages would convert to over time.

CPython will probably never go away due to many private users of the old api, but beginning the work towards implementation independancy in the package ecosystem at large could allow _language compatible_ runtimes with V8/JSCore/LuaJIT-like performance for most new projects.

It all depends on the entire community though and that in turn depends on the goodwill of the CPython team to support this.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Wednesday December 13, 2023 @11:20PM (#38637738)
I should clarify that LuaJIT is not universally used either, because LuaJIT doesn't support anything after Lua 5.1 among other reasons. People often claim that Lua is a relatively speedy language due to the existence of LuaJIT but it's not entirely correct.
Re:How Many Lines of C It Takes to Execute a and B in Python? by whizzter on Saturday December 16, 2023 @05:51AM (#38663325)
It DIDN'T because Mike Pall(LuaJIT author) was on a hiatus from develoment. He's resumed work since and many 5.2+ features has been incorporated now even if the biggest language-turd (1: _ENV) is explicitly incompatible.

The problem is that _ENV explicitly exposes the lexical environment as regular objects prohibiting optimizations, even JavaScript has _removed_ a similar feature (2: the with statement) when running in "strict" mode to simplify optimizations.

LuaJIT _could_ implement the _ENV blocks but it'd seep into large parts of the codebase as ugly special cases that'd slow down all code in related contexts (thus possibly breaking much performance for code in seemingly unrelated places to where _ENV exists).

To compare from an implementation optimization perspective, exposing _ENV is actually __worse__ than what CPython has with the GIL for example.

Luckily "with"-statements in JS was seldomly used so implementers ignored it's existence as long as it's not used(but still have to consider it in implementations, thus adding more workload), but it's an wart that will kill many optimizations if used.

For most practical purposes most people are fine without "with" or _ENV and the languages are fast enough.

https://luajit.org/extensions.html

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Re:How Many Lines of C It Takes to Execute a and B in Python? by steveklabnik on Monday December 11, 2023 @03:54PM (#38605373)
I am going to answer this question in a roundabout way: first showing examples of different code gen in Rust, because it is more straightforward, but then I will reach for an example with Ruby, because I know it better than Python, but I believe it is similar enough that you will get the gist.

If I write a function like this in Rust:

  pub fn add(x: i32, y: i32) -> i32 {
      x + y 
  }
this will compile to this assembly (on x86_64):

  add:
    leal (%rdi,%rsi), %eax
    retq
two instructions. This is because in Rust, free functions exist, have a name, and they are called by name. There's an additional twist here though too, let's check it out in debug mode, with optimizations off:

  add:
    subq $24, %rsp
    movl %edi, 16(%rsp)
    movl %esi, 20(%rsp)
    addl %esi, %edi
    movl %edi, 12(%rsp)
    seto %al
    testb $1, %al
    jne .LBB0_2
    movl 12(%rsp), %eax
    addq $24, %rsp
    retq

  .LBB0_2:
    leaq str.0(%rip), %rdi
    leaq .L__unnamed_1(%rip), %rdx
    movq core::panicking::panic@GOTPCREL(%rip), %rax
    movl $28, %esi
    callq *%rax
    ud2
There's a few things going on here, but the core of it is that in Rust, in debug mode, overflow of addition is checked, but in release mode, wrapping is okay, and so the compiler can eliminate the error path. This is an example of language semantics dictating particular implementation: if I require overflow checks, I am going to get more code, because I have to perform the check. If I do not require the checks, I get less code, because I do not perform the checks. (Where this gets more interesting is in larger examples where the checks get elided because the compiler can prove they aren't necessary, but this is already a tangent of a tangent.)

In Ruby, there are no free functions. If I write a similar add function:

  def add(x, y)
    x + y
  end
This function is not a free function: it is a new private method on the Object class. When you invoke a function in Ruby, it's not like Rust, where you simply find the function with the name you're invoking, and then call it. You instead perform "method lookup," which has some details I will elide, but for the purposes of this discussion, the idea is that you first look at the receiver to see if it has the add method defined, and then if it does not, you look at the receivers' parent class, and if it's not there, you keep going until you hit the top of the hierarchy. Once the method definition is found, you then invoke it.

Now, it's not as if Rust doesn't also have method lookup (though the algorithm is entirely different), but Rust's design means that method lookup (in the vast majority of cases) is a compile-time thing: the lookup happens while you're building the software, and then at runtime, it simply calls the function that you found.

So why can't Ruby run method lookup at compile time? Well, for one, I left out an important second step: Ruby provides a method called method_missing, as a metaprogramming tool. What this means is, if we look the whole way up the object hierarchy and do not find a method named add, we will then re-traverse the entire ancestor tree again, instead invoking each class's method_missing method on the way. method missing takes the name of the method that was trying to be called, the arguments to it, and any block passed to it, and you can then do stuff to figure out if you want to handle this. This means that, even if no add function is defined, it still may be possible for the call to succeed, thanks to a method_missing handler.

Okay well why can't we do that at compile time? Well, Ruby also lets you redefine functions at runtime at basically any time. The define_method method can be called and generate a method on anything, anywhere you want, for whatever reason. You could do this based on user input, even! And yes, that would be a terrible idea, and you probably shouldn't do it, but the implementation of the language requires at least some sort of runtime computation to pull this off in the general case.

Now, I also want to point out that in my understanding, there's caching on method lookup, so that can help reduce the cost in many scenarios. But the point stands that the language has features that Rust does not, and those features mean that certain things must be more expensive than languages that do not have those features.

> can we can imagine an alternate universe Python that's as close as possible to our Python, except really fast? What would be different?

We could, but you lose compatibility with most Python code, and so you're effectively creating a new language. People do try this though, Mojo being an example of this very recently. I am excited to see how it goes.

Re:How Many Lines of C It Takes to Execute a and B in Python? by andai on Monday December 11, 2023 @04:38PM (#38605867)
Thanks. That's fascinating about Ruby, I'll have to look into that.

I'm not an expert on Python but I don't see how Python is significantly more dynamic than e.g. JavaScript. I think PyPy and JS performance is comparable (or at least within the same order of magnitude), so I think it largely comes down to implementation, i.e. prioritizing performance.

I think if it had been Python (or Ruby for that matter) in the browser instead of JS, it would run about as fast as JS does today.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lmm on Monday December 11, 2023 @05:28PM (#38606342)
> I'm not an expert on Python but I don't see how Python is significantly more dynamic than e.g. JavaScript.

JS has much less in the way of magic methods that can affect "normal" object behaviour, and it doesn't have metaclasses in the way that Python does at all. Most of this customization goes unused most of the time, but the runtime still has to handle it in case it's being used this time.

Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Tuesday December 12, 2023 @02:31AM (#38610692)
You should have added Ruby JITs into the explanation, with the related generated Assembly code. :)
Re:How Many Lines of C It Takes to Execute a and B in Python? by steveklabnik on Tuesday December 12, 2023 @12:19PM (#38615222)
Yeah that would be fun but I don't have a Ruby environment installed and the comment is already getting very long; if I ever turn this into a blog post someday maybe I will add that :)
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Tuesday December 12, 2023 @06:16PM (#38620180)
You just happened to post a day after "Ruby 3.3.0-Rc1 Released" "many performance improvements especially YJIT"

https://news.ycombinator.com/item?id=38599293

Re:How Many Lines of C It Takes to Execute a and B in Python? by esafak on Monday December 11, 2023 @02:18PM (#38604159)
"Tech debt doesn't matter!"

"We're going to redesign it the right way after we get this version out the door!"

Re:How Many Lines of C It Takes to Execute a and B in Python? by wongarsu on Monday December 11, 2023 @03:34PM (#38605151)
Arguably those redesigns might have happened if the Python 2->3 transition hadn't received a decade of extremely vocal pushback
Re:How Many Lines of C It Takes to Execute a and B in Python? by fullspectrumdev on Monday December 11, 2023 @05:22PM (#38606280)
What’s funny is the breaking change that caused us the most headaches with 2->3 was the changes to fucking print.

I’m still finding broken print as a statement instead a function issues in codebases, somehow.

Re:How Many Lines of C It Takes to Execute a and B in Python? by pwdisswordfishc on Tuesday December 12, 2023 @09:55AM (#38612930)
It’s the easiest one to fix, though. 2to3 does it easily. If it were the only change, we would not be having this conversation. It might have even not deserved a major version bump (given that even minor releases of Python don't conserve backwards compatibility).
Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Monday December 11, 2023 @09:02PM (#38608348)
> In the late 1990s and early 200xs, there were a lot of claims that there was no such thing as a "slow language", that all languages can be run as quickly as C if you just built a sufficiently smart compiler and/or runtime.

I think "slow language" never meant that way. It was more like a counterpoint to the claim that there are inherent classes of languages in terms of performance, so that some language is (say) 100x or 1000x slower than others in any circumstances. This is not true, even for Python. Most languages with enough optimization works can be made performant enough that it's no slower than 10x C. But once you've got to that point, it can take disproportionally more works to optimize further depending on specific designs.

> If I were designing a language to be slow, but not like stupidly slow just to qualify as an esolang, but where the slowness still contributed to things I could call "features" with a straight face, it would be hard to beat Python.

Ironically, Python's relative slowness came from its uniform design which is generally a good thing. This is distinct from a TCL-style "everything is a string" you've said, because the uniform design had a good intent by its own.

If you have used Python long enough you may know that Python originally had two types of classes---there was a transition period where you had to write `class Foo(object):` to get the newer version. Python wanted to remove a blur between builtin objects and user objects and eventually did so. But no one at that time knew that the blur is actually a good thing for optimization. Python tried to be a good language and is suffering today as a result.

Re:How Many Lines of C It Takes to Execute a and B in Python? by jerf on Tuesday December 12, 2023 @09:36AM (#38612644)
"If you have used Python long enough you may know that Python originally had two types of classes"

Yes, because that's also the era where this claim was flying around.

I'd say that each individual person may have their own read on what the claim meant, but certainly the way it was deployed at anyone who vaguely complained that Python was kind of slow shows that plenty of people in practice read it as I've described... that if we just wait long enough and put enough work into it, there would be no performance difference between Python and C. In 2023 we can look back with the perspective that this seems to be obviously false, so they couldn't possible have meant that, but they didn't have that perspective, and so yes they can have meant that. "Sufficiently smart compiler" was just starting to be a derogatory term. I also remember and lightly participated in the c2.com discussions on that, which may also contribute to my point that, yes, there definitely were people who truly believed "sufficiently smart compilers" could exist and were just a matter of time.

As for proportions, it's impossible to tell. Internet discussions (yea verily including this very one) in general are difficult to ascertain that from because almost by definition only outliers are participating in the discussion at all. Obviously by bulk of programmers, most programmers had simply never considered the question at all.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Tuesday December 12, 2023 @11:52PM (#38622822)
Yeah, I agree everyone may have different anecdotes, for my case though I heard more of the "Python as glue code" arguments and never heard that Python proper can be as fast as C. I've used Python since 2.3, so maybe that argument was more prevalent before?
Re:How Many Lines of C It Takes to Execute a and B in Python? by ngcc_hk on Thursday December 14, 2023 @05:45PM (#38648439)
Same here. Never heard of python can be fast. It is not what it is originally for.
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Tuesday December 12, 2023 @01:26PM (#38616232)
> Most languages with enough optimization works can be made performant enough that it's no slower than 10x C.

Maybe if we take the slowest C program, CPython no slower than 50x ?

https://benchmarksgame-team.pages.debian.net/benchmarksgame/...

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Tuesday December 12, 2023 @11:08PM (#38622534)
CPython had many other concerns besides from performance, and PyPy is much closer to my quote I believe.
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Wednesday December 13, 2023 @02:32PM (#38632984)
fwiw "How many lines of C it takes to execute a + b in Python" was explicitly about CPython.

fwiw PyPy doesn't seem to have been released in "the late 1990s".

Re:How Many Lines of C It Takes to Execute a and B in Python? by spacechild1 on Monday December 11, 2023 @01:53PM (#38603809)
Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Monday December 11, 2023 @11:09PM (#38609326)
They reside in metatables, which are only optionally linked to ordinary objects. Python magic methods are a part of the core object protocol.
Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Tuesday December 12, 2023 @02:26AM (#38610658)
Smalltalk, SELF and Common Lisp are full of dynamic magic, you can in a single function call change the representation of all instances of a given object during program execution, at any given time break into the debugger and change whatever you feel like and resume execution, dynamically load code from the network with side effects on the running program, and many other crazy things.

Yet, not only are they in the genesis of JIT compiler research, their JITs are quite good, and their results went directly into JavaScript JITs research.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Tuesday December 12, 2023 @02:34AM (#38610719)
Is there any direct comparison though? Because it can be alternatively argued that these dynamic languages needed new JIT techniques for performance, but they especially work well for more constrained languages like JS. I don't think Smalltalk was ever a good fit for number crunching, for example.
Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Tuesday December 12, 2023 @06:58AM (#38611085)
Better than CPython, regardless of how you put it.
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Tuesday December 12, 2023 @01:11PM (#38616000)
Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Tuesday December 12, 2023 @11:10PM (#38622543)
Exactly. Comparing with CPython is too easy and arguably unfair, Smalltalk should be compared with JS instead and I think it has no chance in that setting.
Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Wednesday December 13, 2023 @02:41AM (#38623870)
Why should it be compared?

We are not comparing Smalltalk JITs to Javascript JITs.

The whole point of this conversation is CPython refusing to add one, and the lame excuses regarding its dynamic capabilities, when more dynamic languages have had a JIT for decades.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Wednesday December 13, 2023 @05:02AM (#38625068)
First, because CPython had more concerns than what Smalltalk implementations have, so such comparison would be unfair to Python. (See my topmost comment for example.)

Second, my question was about the possibility that Smalltalk and others were unbearably slow without JIT, so JIT was not a matter of choice for them. I'm not aware of Smalltalk implementations that don't have JIT, so it would be easier to compare Smalltalk with another well-optimized JIT implementation instead---in this case JS.

Re:How Many Lines of C It Takes to Execute a and B in Python? by whizzter on Wednesday December 13, 2023 @05:48PM (#38635290)
Not much in the Python language is categorically worse than features within JS when it comes to JIT creation.

My thesis work was on AOT JS compilation, in it I refer to a bunch of experimental Python runtimes, Self,etc and the main issues in all these papers were basically the of same kind.

Heck, even PyPy exists and iirc when it comes to the core language is almost entirely compatible (except for code that relies on ref-counting semantics but that code should apparently big fixed anyhow).

https://www.pypy.org/compat.html

The real summary is: CPython is a turd in many ways, the old C api holds it back and the community hasn't put the effort into using cross-implementation compatible C-bindings instead making PyPy or others a second class citizen.

Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Wednesday December 13, 2023 @02:39AM (#38623846)
CPython is the one being compared here, and besides Pharo, better use an industrial strength one, like Cincom Smalltalk.
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Wednesday December 13, 2023 @02:53PM (#38633306)
Cincom Smalltalk is the one being compared.
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Tuesday December 12, 2023 @01:08PM (#38615949)
So if one was "Prototyping a Real-Time Embedded System in Smalltalk" one might 'improve frequently invoked methods by recoding, possibly as “primitive” functions in a lower level language such as C or assembler'.

https://dl.acm.org/doi/pdf/10.1145/74878.74904

Re:How Many Lines of C It Takes to Execute a and B in Python? by pjmlp on Wednesday December 13, 2023 @02:42AM (#38623883)
CPython is up to date with one specific Smalltalk implementation in 1987, when an ESP32 has better hardware resources than those systems, what a great achievement!
Re:How Many Lines of C It Takes to Execute a and B in Python? by igouy on Wednesday December 13, 2023 @02:51PM (#38633285)
One way Smalltalk was made a better fit for number crunching: primitives.
Re:How Many Lines of C It Takes to Execute a and B in Python? by whizzter on Wednesday December 13, 2023 @05:21PM (#38635037)
Magic methods are not that "hard" to optimize (as long as you don't overload the add,etc operators of f.ex. the Number class in JS). I'm gonna use numbers and addition as an example here.

First off is the value model, the Python runtime handles ALL values as objects and that's fine for an initial naive runtime. All fast/modern language runtimes however use value models/encodings that fits "fast" values directly into machine register at the lowest level.

V8 has(had?) "small-ints" and objects (doubles,strings,etc) by setting the lowest bit in a register for pointers and otherwise dealing with them as numbers. So a+b when JIT'ed has a check (or stored knowledge from a previous opertion to elide the check) that both a and b are integers, if that is true then the actual addition is one single machine addition. if that ISN'T true then a more complex machinery is invoked that could methods like double-dispatch to see if more complex processing (like a "magic" method) is needed. This is how as JS engine handles that + behaves differently between numbers, strings, BigInt's, Date object's,etc.

(Other JS engines and LuaJIT use something called NaN/NuN tagging that also allows for quick passing of numbers w/o allocations and only a few small extra checks)

Re-implementing Python, you'd probably choose a small-int optimization (to better support Pythons seamless bigints) for values, put a runtime specific magic to the number add and make some kind of hook that detects writes to it from user code. Patching that from user code would trigger de-optimizations but for most applicataions it could continue running with optimized paths.

And even with larger objects (like heap-allocated BigInt's) a JS runtime can use inline caching to direct the runtime to fast direct dispatches, and then teams like the V8 team can detect commonly used objects that are often used and create fast-paths. A list addition for example will use common "slow" paths for dispatch but that's ok since it's an inherently slow operation that often involves allocations of some sort so the _relative_ overhead is fairly small in the big picture.

All this naturally assumes that you have the machinery in place, once in place though you can make simple code (numeric additions) fast while retaining magic for more complex objects (bigint, list,string,etc).

Tl;Dr; once you have that kind of optimizing in place, expensive processing can be allowed in special cases in slow paths thanks to type-guards, but 95% of the code will run the fast paths and having that handling in places with speed will give you most wins.

Re:How Many Lines of C It Takes to Execute a and B in Python? by lifthrasiir on Wednesday December 13, 2023 @11:16PM (#38637716)
Instead of individually replying your comments, let me answer them at once here, because I agree you are correct in principle but think you are still missing my points.

Modern tracing JIT engines indeed work by (heavy) specialization, often using multiple underlying representations for single runtime type. I think V8 has at least four Array representations? After many enough specializations it is possible to get a comparable performance even for Python. The question is how many, however.

For a long time, most dynamically typed languages and implementations didn't even try to do JIT because of its high upfront cost. The cost is much lower today---yet still not insignificant enough to say it's no-brainer to do so---, but that fact was not that obvious 20 years ago. Ruby was also one of them, and YJIT was only possible thanks to Shopify's initial works. Given an assumption that JIT is not feasible, both CPython developers and users did a lot of things that further complicate eventual JIT implementations. C API is one, which is indeed one of the major concern for CPython, but a highly customized user class is another. Herein lies the problem:

> Magic methods are not that "hard" to optimize (as long as you don't overload the add,etc operators of f.ex. the Number class in JS).

Indeed, it is very unusual to subclass `Number` in JS, however it is less unusual to subclass `int` in Python, because it is allowed and Python made it convenient. I still think a majority of `int` will use the built-in class and not subclasses, but if it's the only concern, Psyco [1] should have been much popular when it came out because it should have handled such cases perfectly. In reality Psyco was not enough, hence PyPy.

[1] https://psyco.sourceforge.net/introduction.html

At this point I want to clarify that magic methods in Python are much more than mere operator overloading. For example, properties in JS are more or less direct (`Object.defineProperty` and nowadays a native syntax), but in Python they are implemented via descriptors, which are a nested object with yet another dunder methods. For example this implements the `Foo.bar` property:

    class Foo:
        class Bar:
            def __get__(self, obj, objtype=None): return 42
        bar = Bar()
In reality everyone will use `bar = property(lambda self: 42)` or equivalent instead, but that's how it works underneath. And the nested object can do absolutely anything. You can specialize for well-known descriptor types like `property`, but that wouldn't be enough for complex Python codebases. This is why...

> This is how as JS engine handles that + behaves differently between numbers, strings, BigInt's, Date object's,etc.

...is not the only thing JS engines do. They also have hidden classes (aka shapes) that are recognized and created in runtime, and I think it was one of innovations pioneered by V8---outside of the PL academia of course. Hidden classes in Python would be more complex than those in JS for this added flexibility and resulting uses. And JS hidden classes are not even that simple to implement.

After decades of JIT not in sight, and a non-trivial amount of work to get a working JIT even after that, it is not unreasonable that CPython didn't try to build JIT for a long time and the current JIT work is still quite conservative (it uses a copy-and-patch compilation to reduce the upfront cost). CPython did do lots of optimizations possible in interpreters though, many things mentioned above are internally cached for performance. One can correctly argue that such optimizations were not steady enough---for example, adaptive opcodes in 3.11 are something Java HotSpot used to do more than 10 years ago.

Re:How Many Lines of C It Takes to Execute a and B in Python? by KMag on Monday December 11, 2023 @03:32PM (#38605115)
> LuaJIT managed with less with a focused language and a really capable lead.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by ngcc_hk on Thursday December 14, 2023 @06:07PM (#38648673)
Finally got the proof that time travel did exist. But I wonder many like bitcoin might be. Then the pin drop could the whole python is a future ai coming in and prevent us from optimise and squeeze them out. They need the glue language. Ai depend upon it. Hence it is all for ai.
Re:How Many Lines of C It Takes to Execute a and B in Python? by sp332 on Monday December 11, 2023 @09:04AM (#38600708)
The last couple of CPython versions have had dramatic speed improvements, so that demonstrates your point but also gives some hope that things are changing on that front.
Re:How Many Lines of C It Takes to Execute a and B in Python? by coldtea on Monday December 11, 2023 @11:26AM (#38601967)
Dramatic? Barely. Even less than half of the non-dramatic speed improvements they promised. The promise was like "5 times faster in the next 4 releases", and the improvements in 2 releases thus far was like 20% at best (so not even 2x faster).

Compared to JS pre-and-after modern engines it's a tiny improvement.

Re:How Many Lines of C It Takes to Execute a and B in Python? by mseepgood on Monday December 11, 2023 @09:38AM (#38601008)
If this is by design and it optimizes for simplicity and easy interoperability with C, why would you assess its quality as 'good software' based on criteria that are non-goals?
Re:How Many Lines of C It Takes to Execute a and B in Python? by Asraelite on Monday December 11, 2023 @10:13AM (#38601321)
In my eyes, "good software" does not necessarily just mean something that accomplishes its goals. You can set a goal of being bad, and that's kind of what CPython is doing.

Of course, "good" and "bad" are relative. If you don't care about performance then there's nothing wrong with CPython.

Re:How Many Lines of C It Takes to Execute a and B in Python? by acqq on Monday December 11, 2023 @12:21PM (#38602465)
I agree with that estimate, I think it was really the idea of Python to be less than "good" by design.

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.
Re:How Many Lines of C It Takes to Execute a and B in Python? by monoprotic on Monday December 11, 2023 @01:17PM (#38603269)
There has been discussion of this change a few times, e.g. https://bugs.python.org/issue44603

I generally agree with your overall sentiment, but I think it's important to note that the behavior is _not_ special handling; it's just the normal `repr` behavior at the REPL, where `exit` is an object like any other, and `repr(exit)` is that message.

Re:How Many Lines of C It Takes to Execute a and B in Python? by acqq on Wednesday December 13, 2023 @08:58AM (#38627402)
Whoever types exit in REPL will never care what "repr(exit)" does.

Python has a lot excuses about the need to remain "consistent" but the reality isn't so:

    >>> x = open( "/tmp/whatever123", "w" )
    >>> close( x )
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'close' is not defined. Did you mean: 'cosh'?
    ...    
    >>> x.close()
    >>>
    >>> x = "tttt"
    >>> x.len()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>    
    ...
    >>> len( x )
    4
Re:How Many Lines of C It Takes to Execute a and B in Python? by zitterbewegung on Monday December 11, 2023 @02:46PM (#38604533)
I think this is to be consistent that exit is not a statement but a function. This was done with print. 3.0 was an ergonomic fix for cpython developers and language consistency fixes (also redoing the Unicode implementation).
Re:How Many Lines of C It Takes to Execute a and B in Python? by heyodai on Monday December 11, 2023 @12:57PM (#38602969)
Yeah, that message is a pet peeve of mine. Like, you know what I'm trying to do.
Re:How Many Lines of C It Takes to Execute a and B in Python? by Smaug123 on Monday December 11, 2023 @01:43PM (#38603667)
It sort of doesn't! It's just doing exactly the same thing it would do with any other identifier: it's printing its `repr`. Try `repr(exit)`!
Re:How Many Lines of C It Takes to Execute a and B in Python? by a1369209993 on Monday December 11, 2023 @04:53PM (#38606038)
More to the point, try `[len,exit,repr]`. Consider what would happen if `exit.__repr__()` did terminate the program.
Re:How Many Lines of C It Takes to Execute a and B in Python? by zitterbewegung on Monday December 11, 2023 @09:41AM (#38601037)
I don't disagree with you but, now you can retrofit a JIT into python. https://blog.pyston.org/2022/09/29/announcing-3-7-3-10-suppo...
Re:How Many Lines of C It Takes to Execute a and B in Python? by acqq on Monday December 11, 2023 @12:12PM (#38602370)
"We think of the breakdown roughly as follows: of our roughly 30% original speedup, 10% is going into Pyston-lite, 10% was done independently by the CPython team between 3.8 and main, and the remaining 10% we are hoping to contribute back upstream."

To compare with Javascript: if I remember, as it appeared, V8 JIT was orders of magnitude faster, compared to the interpreted code.

Re:How Many Lines of C It Takes to Execute a and B in Python? by zitterbewegung on Monday December 11, 2023 @02:43PM (#38604488)
There was also a bunch of effort being put into efficiency of JavaScript. But now the tables have been changed and Microsoft is putting a large amount of effort into Python .
Re:How Many Lines of C It Takes to Execute a and B in Python? by heavyset_go on Monday December 11, 2023 @10:48AM (#38601615)
Recent CPython development has been towards optimizations and addressing use cases that benefit from optimizations, some coming from the faster CPython initiative. You might just get your JIT[1].

At the same time, I also agree with your sentiment.

[1] https://github.com/faster-cpython/ideas/wiki/Workflow-for-3....

Re:How Many Lines of C It Takes to Execute a and B in Python? by nostrademons on Monday December 11, 2023 @12:19PM (#38602449)
It's great software for the use case that Python is intended for. Python is supposed to be glue code. You embed a scripting runtime in your application, do all the heavy lifting in C, but configure your building blocks in Python so that you can easily reconfigure them as needs change.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by oivey on Monday December 11, 2023 @02:13PM (#38604100)
Arguably no one’s goal is to glue pieces of C together. That’s too abstract. Their goal is to do something like write a performant web server, maybe easily and quickly. Python’s approach is one way to do that, but there are other ways that might be better. Having to write code in two languages to solve a problem, one of which that is difficult to write and has lots of footguns, has some clear downsides.
Re:How Many Lines of C It Takes to Execute a and B in Python? by nostrademons on Monday December 11, 2023 @03:21PM (#38604987)
Basically nobody's goal is to "write a performant web server" either, it's to serve data to customers quickly and efficiently. And that highlights why it may not be worth optimizing the Python web ecosystem. There are so many newer alternatives for that overall goal - Firebase, Amazon Lambda, ditching webapps for native mobile, etc - that it may not make sense to try to optimize an application server unless you work for Google or Amazon, because very few people setup a standalone webserver on bare-metal hardware anymore, and those that do probably aren't going to try a new and untested alternative.
Re:How Many Lines of C It Takes to Execute a and B in Python? by kazinator on Monday December 11, 2023 @05:00PM (#38606093)
Nobody's goal is to serve data to customers quickly and efficiently either. It's more like, get this startup acquired and buy a ranch in New Zealand.
Re:How Many Lines of C It Takes to Execute a and B in Python? by SilasX on Thursday December 14, 2023 @12:46AM (#38638226)
Haha you might like this old comment I made where I gradually go up the abstraction ladder about what you "really care" about (in the unlikely event you see this comment):

https://news.ycombinator.com/item?id=9777816

Root of the subthread: https://news.ycombinator.com/item?id=9775799

Re:How Many Lines of C It Takes to Execute a and B in Python? by nerdponx on Monday December 11, 2023 @02:28PM (#38604296)
Ritchie and Thompson might disagree with you.
Re:How Many Lines of C It Takes to Execute a and B in Python? by eesmith on Monday December 11, 2023 @03:00PM (#38604718)
Gluing pieces of C together was literally the reason I started using Python back in the 1990s.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by bb88 on Monday December 11, 2023 @02:07PM (#38604022)
I've been playing around with HTMX with Django, and it seems simple enough for server side rendering. It works well with the Django templating system.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by kazinator on Monday December 11, 2023 @04:59PM (#38606086)
> for the use case that Python is intended for

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by jasode on Monday December 11, 2023 @05:59PM (#38606691)
>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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by kazinator on Monday December 11, 2023 @06:13PM (#38606793)
I liked it back when we used "use case" for that concept with the actor executing a concrete interaction with a system to achieve a specific goal, and "architecture" for how the pieces fit together, without mixing or equating the two. :)
Re:How Many Lines of C It Takes to Execute a and B in Python? by MR4D on Monday December 11, 2023 @05:23PM (#38606291)
From https://www.python.org/about/ (mouse over the "About" menu) :

'Python is a programming language that lets you work more quickly and integrate your systems more effectively.'

Re:How Many Lines of C It Takes to Execute a and B in Python? by spookie on Monday December 11, 2023 @05:54PM (#38606636)
This is one of the biggest misunderstandings in computing for the last decade, I feel.
Re:How Many Lines of C It Takes to Execute a and B in Python? by kazinator on Monday December 11, 2023 @05:59PM (#38606683)
That's not a specific use case. That's like brochure pitch.
Re:How Many Lines of C It Takes to Execute a and B in Python? by tesdinger on Monday December 11, 2023 @05:37PM (#38606434)
> 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.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by tesdinger on Monday December 11, 2023 @05:49PM (#38606552)
This is the problem with SQL queries and Django Forms I am talking about

https://stackoverflow.com/questions/17330158/django-how-to-u...

Re:How Many Lines of C It Takes to Execute a and B in Python? by matheusmoreira on Monday December 11, 2023 @02:21PM (#38604209)
Just yesterday I compared the small language I created to Python. Was surprised my tree walking interpreter somehow beat Python's bytecode virtual machine at recursive Fibonacci. It was just a simple hyperfine benchmark so I might be confounding code execution performance with the initialization time. Still caught me totally off guard and gave me a huge confidence and motivation boost. I was thinking something like "OK let's see just how bad this thing is" but it actually beat Python at something.
Re:How Many Lines of C It Takes to Execute a and B in Python? by genman on Monday December 11, 2023 @06:43PM (#38607054)
I really enjoined working in Lua.
Re:How Many Lines of C It Takes to Execute a and B in Python? by ouraf on Wednesday December 13, 2023 @08:37AM (#38627127)
Is there any comprehensive comparison and benchmark of intepreted languages or languages with a REPL and analysis of how each interpreter handles common operations?
Re:How Many Lines of C It Takes to Execute a and B in Python? by a_humean on Monday December 11, 2023 @05:17AM (#38599219)
I'm aware that Rust has something similiar for things like `std::collections::HashMap`. By default:

> 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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by yakubin on Monday December 11, 2023 @05:49AM (#38599401)
Which is why the Rust compiler itself uses a non-cryptographic hash, which takes just 3 x86 instructions and can work on 8 bytes at a time: <https://github.com/rust-lang/rustc-hash/blob/master/src/lib....>
Re:How Many Lines of C It Takes to Execute a and B in Python? by eesmith on Monday December 11, 2023 @05:36AM (#38599329)
Python 3.11 appears to have switched to SipHash 1-3 for strings, from 2-4, following the lead of Rust and Ruby. https://github.com/python/cpython/issues/73596

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)
  0
Re:How Many Lines of C It Takes to Execute a and B in Python? by danhau on Monday December 11, 2023 @08:04AM (#38600285)
That’s good though, right? Is there a reason for not using an identity hash (is that the right term?) for integers?
Re:How Many Lines of C It Takes to Execute a and B in Python? by ynik on Monday December 11, 2023 @08:37AM (#38600509)
That depends on the hash table implementation and the distribution of the integers.

For 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).

Re:How Many Lines of C It Takes to Execute a and B in Python? by vhcr on Monday December 11, 2023 @09:11AM (#38600763)
Don't use user-supplied integers on dicts or sets on Python:

>>> {i for i in range(10000)}

Takes 0.005s

>>> {i * sys.hash_info.modulus for i in range(10000)}

Takes 0.76s

Re:How Many Lines of C It Takes to Execute a and B in Python? by petters on Monday December 11, 2023 @05:33AM (#38599312)
Do you mean this post? https://www.reddit.com/r/Python/s/raofvsKCiz That speedup was disputed in the comments. I haven’t tried it myself though
Re:How Many Lines of C It Takes to Execute a and B in Python? by masklinn on Monday December 11, 2023 @06:59AM (#38599829)
https://www.reddit.com/r/Python/comments/mgi4op/comment/gswg...

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by tialaramex on Monday December 11, 2023 @09:24AM (#38600878)
Rust is doing something even more subtle here than just making the hash function a container property. There are two inter-related Rust traits, Hash is a trait which types implement to explain abstractly how to hash that type, but it's written in terms of a Hasher trait so you can drop in a different function with the same API. The Rust standard library provides a derive macro for Hash, so most people can just gesture vaguely at their custom type and have it hashed correctly for any hash functions they need. The naïve approach here easily ends up doing a bad job either colliding hashes for correlated objects in a surprising way or emitting different hashes for equivalent objects because people who make a user defined type probably aren't hashing experts.
Re:How Many Lines of C It Takes to Execute a and B in Python? by masklinn on Monday December 11, 2023 @10:48AM (#38601619)
We can get into the weeds about the details, but what I'm talking about is mostly that in Python (and in most languages really, AFAIK Ruby, Java, or C# are the same to list just a few) objects have to return the hash itself, so the hash function is fixed by the type.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by tialaramex on Monday December 11, 2023 @11:30AM (#38602013)
The derive macro is also key here. Have you ever looked at the machinery needed for Java's URI type to have a halfway useful hashCode implementation? It's pretty elaborate, there's just no way the average programmer will do that work correctly for their own types even ignoring the desire to allow different hash functions. Rust programmers are almost always able to just write #[derive(Hash)] and not worry about it.
Re:How Many Lines of C It Takes to Execute a and B in Python? by tyingq on Monday December 11, 2023 @05:04AM (#38599160)
It looks like you can disable the slower randomized hashing yourself by setting PYTHONHASHSEED to 0. Though I don't know if there's further speedup to be had by using a different hash implementation.

https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHA...

The original issue: https://bugs.python.org/issue13703

Re:How Many Lines of C It Takes to Execute a and B in Python? by masklinn on Monday December 11, 2023 @06:45AM (#38599742)
That only disables the keying of the hash function (sets the initial value to 0), it does not change the hash function.

The hashseed is a per-process value, it has basically no impact on performances.

Re:How Many Lines of C It Takes to Execute a and B in Python? by ynik on Monday December 11, 2023 @05:33AM (#38599307)
AFAIK Python strings cache their hash value. All the hash table lookups for object properties should be compile-time constant strings that reuse the string object, and thus also reuse the cached hash value. It may take 11 hash computations for the first print("hello world"), but the second call shouldn't take any.
Re:How Many Lines of C It Takes to Execute a and B in Python? by eesmith on Monday December 11, 2023 @05:27AM (#38599278)
Your "just in case the software is exposed to the web" should be "exposed to untrusted data." The very old Python hash could be DoS'ed reading a data file. The original randomized version required some feedback to figure out the hash, so generally required some sort of interaction.

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

Re:How Many Lines of C It Takes to Execute a and B in Python? by explaininjs on Monday December 11, 2023 @11:31AM (#38602015)
What's more, you can get a significant speedup from your Python scripts by replacing the inbuilt cpython malloc calls with a static "allocate big chunk of stack at the beginning and I'll manage it myself" implementation, falling back to malloc as needed if it grows beyond that. A college class in perf engineering I TA'd did this, the results even a beginner could achieve were compelling, the top of the class produced results quite remarkable indeed..

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by anitil on Monday December 11, 2023 @09:34PM (#38608600)
I'd love to see an example of this if you happen to have one available. I hit a startup-time issue in a previous life, and I wish I had spent the time looking at it back then
Re:How Many Lines of C It Takes to Execute a and B in Python? by explaininjs on Tuesday December 12, 2023 @02:28AM (#38610677)
A template repo can be found here https://github.com/JacksonKearl/cpython, but it does not implement an ideal malloc, just a baseline one - I am not sure if it is still being used as an assignment.

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.

Re:How Many Lines of C It Takes to Execute a and B in Python? by anitil on Tuesday December 12, 2023 @11:03PM (#38622506)
Thankyou so much!
Re:How Many Lines of C It Takes to Execute a and B in Python? by 2OEH8eoCRo0 on Monday December 11, 2023 @12:25PM (#38602522)
> I'd much prefer to have a "I'm offline, please run twice as fast!"

If I know anything about programmers, it's that everyone would just use the "go faster" flag by default.

Re:How Many Lines of C It Takes to Execute a and B in Python? by xorcist on Tuesday December 12, 2023 @02:20AM (#38610609)
Yet ~ nobody uses PyPy by default. Speed is clearly not the top consideration for most Python programmers.
Re:How Many Lines of C It Takes to Execute a and B in Python? by 60secs on Monday December 11, 2023 @01:40PM (#38603602)
So your solution to if statements is to add more if statements?
Re:How Many Lines of C It Takes to Execute a and B in Python? by matheusmoreira on Monday December 11, 2023 @02:33PM (#38604363)
Hash function security is certainly a concern due to hash flooding attacks which force worst case performance hash table lookup and leads to denial of service.

https://peps.python.org/pep-0456/

Re:How Many Lines of C It Takes to Execute a and B in Python? by tesdinger on Monday December 11, 2023 @06:04PM (#38606729)
A lot of code never sees data input by untrusted sources. Just let me ignore the possible attacks and run python faster on my own data.