9 ms·
Python: The Optimization Ladder
- Ralfp 7mo agoCPython 3.13 went further with an experimental copy-and-patch JIT compiler -- a lightweight JIT that stitches together pre-compiled machine code templates instead of generating code from scratch. It's not a full optimizing JIT like V8's TurboFan or a tracing JIT like PyPy's; Good news. Python 3.15 adapts Pypy tracing approach to JIT and there are real performance gains now: https://github.com/python/cpython/issues/139109 https://github.com/python/cpython/issues/139109 https://doesjitgobrrr.com/?goals=5,10 https://doesjitgobrrr.com/?goals=5,10
- josalhor 7mo agoWhile this is great, I expected faster CPython to eventually culminate into what YJIT for Ruby is. I'm not sure the current approaches they are trying will get the ecosystem there.
- kenjin4096 7mo agoI implemented most of the tracing JIT frontend in Python 3.15, with help from Mark to clean up and fix my code. I also coordinated some of the community JIT optimizer effort in Python 3.15 (note: NOT the code generator/DSL/infra, that's Mark, Diego, Brandt and Savannah). So I think I'm able to answer this. I can't speak for everyone on the team, but I did try the lazy basic block versioning in YJIT in a fork of CPython. The main problem is that the copy-and-patch backend we currently have in CPython is not too amenable to self-modifying machine code. This makes inter-block jumps/fallthroughs very inefficient. It can be done, it's just a little strange. Also for security reasons, we tried not to have self-modifying code in the original JIT and we're hoping to stick to that. Everything has their tradeoffs---design is hard! It's not too difficult to go from tracing to lazy basic blocks. Conceptually they're somewhat similar, as the original paper points out. The main thing we lack is the compact per-block type information that something like YJIT/Higgs has. I guess while I'm here I might as well make the distinction: - Tracing is the JIT frontend (region selection). - Copy and Patch is the JIT backend (code generation). We currently use both. PyPy uses meta-tracing. It traces the runtime itself rather than the user's code in CPython's tracing case. I did take a look at PyPy's code, and a lot of ideas in the improved JIT are actually imported from PyPy directly. So I have to thank them for their great ideas. I also talk to some of the PyPy devs. Ending off: the team is extremely lean right now. Only 2 people were generously employed by ARM to work on this full time (thanks a lot to ARM too!). The rest of us are mostly volunteers, or have some bosses that like open source contributions and allow some free time. As for me, I'm unemployed at the moment and this is basically my passion project. I'm just happy the JIT is finally working now after spending 2-3 years of my life on it :). If you go to Savannah's website [1], the JIT is around 100% faster for toy programs like Richards, and even for big programs like tomli parsing, it's 28% faster on macOS AArch64. The JIT is very much a community effort right now. [1]: https://doesjitgobrrr.com/?goals=5,10 https://doesjitgobrrr.com/?goals=5,10 PS: If you want to see how the work has progressed, click "all time" in that website, it's pretty cool to see (lower is faster). I have a blog explaining how we made the JIT faster here https://fidget-spinner.github.io/posts/faster-jit-plan.html https://fidget-spinner.github.io/posts/faster-jit-plan.html.
- vovavili 7mo agoThank you for your contributions to the Python ecosystem. It definitely is inspiring to see Python, the language to which I owe my career and interest in tech, grow into a performant language year by year. This would not have been possible without individuals like you.
- pjmlp 7mo agoNow this is great to know.
- seanwilson 7mo ago> The real story is that Python is designed to be maximally dynamic -- you can monkey-patch methods at runtime, replace builtins, change a class's inheritance chain while instances exist -- and that design makes it fundamentally hard to optimize. ... > 4 bytes of number, 24 bytes of machinery to support dynamism. a + b means: dereference two heap pointers, look up type slots, dispatch to int.__add__, allocate a new PyObject for the result (unless it hits the small-integer cache), update reference counts. Would Python be a lot less useful without being maximally dynamic everywhere? Are there domains/frameworks/packages that benefit from this where this is a good trade-off? I can't think of cases in strong statically typed languages where I've wanted something like monkey patching, and when I see monkey patching elsewhere there's often some reasonable alternative or it only needs to be used very rarely.
- LtWorf 7mo agoI've used a library that patches the zipfile module to add support for zstd compression in zipfiles. In python3.14 the support is there, but 2 years ago you could just import this library and it would just work normally.
- NeutralForest 7mo agoThere are some use cases for very dynamic code, like ORMs; with descriptors you can add attributes + behavior at runtime and it's quite useful. Anyways, breaking metaprogramming and more dynamic features would mean python 4 and we know how 2 -> 3 went. I also don't think it's where the core developers are going. Also also, there are other things I'd change before going after monkey patching like some scoping rules, mutable defaults in function attributes, better async ergonomics, etc.
- bloaf 7mo agoI've always thought the flexibility should allow python to consume things like gRPC proto files or OpenAPI docs and auto-generate the classes/methods at runtime as opposed to using codegen tools. But as far as I know, there aren't any libraries out there actually doing that.
- 7mo ago
- __mharrison__ 7mo agoGreat writeup. I've been in the pandas (and now polars world) for the past 15 years. Staying in the sandbox gets most folks good enough performance. (That's why Python is the language of data science and ML). I generally teach my clients to reach for numba first. Potentially lots of bang for little buck. One overlooked area in the article is running on GPUs. Some numpy and pandas (and polars) code can get a big speedup by using GPUs (same code with import change).
- bloaf 7mo agoTaichi, benchmarked in the article, claims to be able to outperform CUDA at some GPU tasks, although their benchmarks look to be a few years old: https://github.com/taichi-dev/taichi_benchmark https://github.com/taichi-dev/taichi_benchmark
- pjmlp 7mo agoAnd doesn't account for cuTitle, NVidia's new API infrastructure that supports writing CUDA directly in Python via a JIT that is based on MLIR.
- kelvinjps10 7mo agoGreat post saved it for when I need to optimize my python code
- rusakov-field 7mo agoPython is perfect as a "glue" language. "Inner Loops" that have to run efficiently is not where it shines, and I would write them in C or C++ and patch them with Python for access to the huge library base. This is the "two language problem" ( I would like to hear from people who extensively used Julia by the way, which claims to solve this problem, does it really ?)
- pjmlp 7mo agoThis problem has been solved already by Lisp, Scheme, Java, .NET, Eiffel, among others, with their pick and choose mix of JIT and AOT compiler toolchains and runtimes.
- eigenspace 7mo agoNo, those languages have not solved it. None of the languages you list there are actually as fast as C for tight inner loops, they sometimes get close under certain circumstances, but they're still very much 2nd class languages in terms of performance. They're only "fast" compared to slow interpreted languages like Python.
- pjmlp 7mo agoYes they have, because those microbenchmarks are tailor made for the winner, using a very specific compiler implementation with language extensions, which apparently is only valid if the language happens to be "C".
- eigenspace 7mo agoThis is such bizarre cope. It's okay for a language to not have first-class numerical performance characteristics. Langauges can have other reasons to exist. Just don't like about the performance, that doesn't help anyone.
- pjmlp 7mo ago
- retsibsi 7mo agoA personal opinion: I would much prefer to read the rough, human version of this article than this AI-polished version. I'm interested in the content and the author clearly put thought and effort into it, but I'm constantly thrown out of it by the LLM smell. (I'm also a bit mad that `--` is now on the em dash treadmill and will soon be unusable.) I'm not just saying this to vent. I honestly wonder if we could eventually move to a norm where people publish two versions of their writing and allow the reader to choose between them. Even when the original is just a set of notes, I would personally choose to make my own way through them.
- arlattimore 7mo agoWhat a great article!
- superlopuh 7mo agoMissing Muna[0][1], I'm curious how it would compare on these benchmarks. [0]: https://www.muna.ai/ https://www.muna.ai/ [1]: https://docs.muna.ai/predictors/create https://docs.muna.ai/predictors/create
- blt 7mo agoSurprised Python is only 21x slower than C for tree traversal stuff. In my experience that's one of the most painful places to use Python. But maybe that's because I use numpy automatically when simple arrays are involved, and there's no easy path for trees.
- tweakimp 7mo agoBe careful with that, numpy arrays can be slower than Python tuples for some operations. The creation is always slower and the overhead has to be worth it.
- __rito__ 7mo agoYeah. Many seem to forget it. For one-off computation tasks, NumPy, PyTorch, JAX have non-trivial overhead, and might even be slower than vanilla Python. Only when repetition, loops, etc. come into the picture, which is recurring in many people’s workflow - JAX or NumPy is worth it.
- blt 7mo agoyes of course, in my field the arrays are large and we're doing nontrivial work per element.
- AlotOfReading 7mo agoYou can turn trees into numpy-style matrix operations because graphs and matrices are two sides of the same coin. I don't see the code for the binary-tree benchmark in the repo to see how it's written, but there are libraries like graphblas that use the equivalence for optimization.
- pjmlp 7mo agoKudos for going through all the existing JIT approaches, instead of reaching for rewrite into X straight away. However if Rust with PyO3 is part of the alternatives, then Boost.Python, cppyy, and pybind11 should also be accounted for, given their use in HPC and HFT integrations.
- repple 7mo agoSignificant AI smell in this write up. As a result, my current reflex is to immediately stop reading. Not judgement on the actual analysis and human effort which went in. It’s just that the other context is missing.
- MonkeyClub 7mo agoI got the same sense, but nowadays I can't be sure whether a text is AI or the writer's style has absorbed LLM tropes.
- jb_hn 7mo agoI didn't notice any signs of AI writing until seeing this comment and re-reading (though I did notice it on the second pass). That said, I think this article demonstrates that focusing on whether or not an article used AI might be focusing on the wrong “problem.” I appreciate being sensitive to the "smell" (the number of low-effort, AI posts flying around these days has made me sensitive too), but personally, I found this article both (1) easy to read and (2) insightful. I think the number of AI-written content lacking (2) is the problem.
- repple 7mo agoYour initial focus is to prioritize which content to consume.
- huseyinkeles 7mo agoThe author is from Turkey (where I’m also originally from). Believe it or not, when you write a blog post in a different language, it really helps to use an LLM, even just to fix your grammar mistakes etc. I assume that’s most likely what happened here too.
- repple 7mo agoI believe it
- shepherdjerred 7mo ago
- Mawr 7mo agoShockingly good article — correct identification of the root cause of performance issues being excessive dynamism and ranking of the solutions based on the value/effort ratio. Excellent taste. Will keep this in my back pocket as a quick Python optimization reference. It's just somewhat unfortunate that I have to question every number and fact presented since the writing was clearly at least somewhat AI-assisted with the author seemingly not being upfront about that at all.
- threethirtytwo 7mo agoBeing upfront about AI-assistance or no AI-assistance doesn't mean shit. Whether AI was involved is independent of what they state and there's no real way to fully prove otherwise.
- perching_aix 7mo ago> language slow > looks inside > the reference implementation of language is slow Despite its content, this blogpost also pushes this exact "language slow" thinking in its preamble. I don't think nearly enough people read past introductions for that to be a responsible choice or a good idea. The only thing worse than this is when Python specifically is outright taught (!) as an "interpeted language", as if an implementation-detail like that was somehow a language property. So grating.
- zahlman 7mo agoWhile I sympathize (and have said similar in the past), language design can (and in Python's case certainly does) hinder optimization quite a bit. The techniques that are purely "use a better implementation" get you not much further than PyPy. Further benefits come from cross-compilation that requires restricting access to language features (and a system that can statically be convinced that those features weren't used!), or indeed straight up using code written in a different language through an FFI. But yes, the very terminology "interpreted language" was designed for a different era and is somewhere between misleading and incomprehensible in context. (Not unlike "pass by value".)
- perching_aix 7mo agoAbsolutely, no doubt about that. I just find it a terrible way to approach from in general, as well as specifically in this case: swapping out CPython with PyPy, GraalPy, Taichi, etc. - as per the post - requires no code changes, yet results in leaps and bounds faster performance. If switching runtimes yields, say, 10x perf, and switching languages yields, say, 100x, then the language on its own was "just" a 10x penalty. Yet the presentation is "language is 100x slower". That's my gripe. And these are apparently conservative estimates as per the tables in the OP. Not that metering "language performance" with numbers would be a super meaningful exercise to begin with, but still. The fact that most people just go with CPython does not escape me either. I do wonder though if people would shop for alternative runtimes more if the common culture was more explicitly and dominantly concerned with the performance of implementations, rather than of languages.
- threethirtytwo 7mo ago>The usual suspects are the GIL, interpretation, and dynamic typing. All three matter, but none of them is the real story. The real story is that Python is designed to be maximally dynamic -- you can monkey-patch methods at runtime, replace builtins, change a class's inheritance chain while instances exist -- and that design makes it fundamentally hard to optimize. ok I guess the harder question is. Why isn't python as fast as javascript?
- 12_throw_away 7mo ago> ok I guess the harder question is. Why isn't python as fast as javascript? Actually there is a pretty easy answer: worldwide, the amount of javascript being evaluated every day is many orders of magnitude higher than the amount of python. The amount of money available for optimizing it has thus been many orders of magnitude higher as well.
- threethirtytwo 7mo agoI mean the technical reasons. Because every reason stated in my quote is applicable to JavaScript as well.
- saagarjha 7mo agoI don’t think the answer is that easy. Python is typically run on the server and JavaScript is client-side, which means that the incentives are aligned to optimize Python rather than JavaScript. I think investment in each follows and the difference is more that JavaScript runs in an isolated environment with a more flexible runtime.
- threethirtytwo 7mo agoNah although his answer wasn’t exactly what I’m looking for he’s not wrong. Python is not optimized because on the backend you just switch to another language that’s faster. That’s the economically optimized thing to do. Can’t do that on the frontend.
- skeledrew 7mo agoI must admit that I'm amused by the people who find the writeup useful but are turned off by the AI "smell". And look forward to the day when all valued content reeks of said "smell"; let's see what detractors-for-no-good-reason do then (yes I'm a bit ticked by the attitude).
- deleted 7mo ago[deleted]
- achierius 7mo agoIsn't this a depressing thought? Regardless of AI, to think that everything we read would come in the same literary style, conveying little of the author, giving no window through which to learn about who they are -- that would be a real loss.
- repple 7mo agoUltimately it’s up to the author to make that explicit choice. I think that AI does and will enhance writing and depth and breadth of analysis one could perform. But, to be trustworthy, people will need to either lay out all cards on the table and/or work on other ways to gain trust over time. Maybe people need to provide some context to communicate what model was used and in which ways. What % of final output is AI vs author. I mean, if I see 100% composed by human author stated somewhere then there’s my cue to at the very least learn a little about the author. Certainly more complexity and discernment for readers. Depressing? In some ways maybe; but I’m kind of optimistic. Imagine what Tolkien could worldbuild armed with AI.. but then it wouldn’t be Tolkien.
- skeledrew 7mo agoNot at all depressing. If authors/creators want readers/consumers to know who they are, then they'll do so in whatever way they consider acceptable to them.
- zahlman 7mo agoWhy is it amusing? How can you suppose that this is not a good reason to object, especially days after https://news.ycombinator.com/item?id=47340079 https://news.ycombinator.com/item?id=47340079 ? I find the style so reflexively grating that it's honestly hard for me to imagine others not being bothered by it, let alone being bothered by others being bothered. Especially since I looked at previous posts on the blog and they didn't have the same problem.
- adsharma 7mo agoMissing: write static python and transpile to rust pyO3 which is at the top of the ladder. Some nuance: try transpiling to a garbage collected rust like language with fast compilation until you have millions of users. Also use a combination of neural and deterministic methods to transpile depending on the complexity.
- tda 7mo agoOne thing with python is that usually I will use one of the many c based libraries to get reasonable speed and well thought out abstractions from the start. I architect around numpy, scipy, shapely, pandas/polars or whatever. So my code runs at reasonable speed from the start. But transpiling to rust then effectively means a complete redesign of the code, data structures, algorithms etc. And I have seen the AI tools really struggle to get it right, as my intent gets lost somewhere. So what I do now (since Claude Code) is write really bare bones (and slow) pure python implementation (like I used to do for numba, pypy or cython ready code), with minimal dependencies. Then I use the REPL, notebooks and nice plotting tools to get a real understanding of the problem space and the intricacies of my algorithm/problem at hand. When done, I let Claude add tests and I ask it to transpile to equivalent Rust and boom! a flawless 1000x speed upgrade in a minutes. The great thing is I don't need to do the mental gymnastics to vectorize code in a write only mode like I've had to do since my Matlab days. Instead I can write simple to read for loops that follow my intent much better, and result in much more legible code. So refreshing! And with pyO3 i can still expose the Rust lib to python, and continue to use Python for glue and plotting
- adsharma 7mo agoCython and all the libs you mention use the c-api, which is the #1 thing python needs to lose to be competitive. I wish someone writes a stdlib without using it. My attempt from a few months ago in a repo under the py2many org.
- gf000 7mo ago> Cython and all the libs you mention use the c-api, which is the #1 thing python needs to lose to be competitive. Quite hard to lose the #1 reason people use the language for.
- markisus 7mo agoI wish there were more details on this part. > Missing @cython.cdivision(True) inserts a zero-division check before every floating-point divide in the inner loop. Millions of branches that are never taken. I thought never taken branches were essentially free. Does this mean something in the loop is messing with the branch predictor?
- pavpanchekha 7mo agoThey're cheap but not free, especially at the front end of the CPU where it's just a lot more instructions to churn through. What the branch predictor gets you is it turns branches, which would normally cause a pipeline bubble, to be executed like straightline code if they're predicted right. It's a bit like a tracing jit. But you will still have a bunch of extra instructions to, like, compute the branch predicate.
- beng-nl 7mo agoWorse, IMO, is the never taken branch taking up space in branch prediction buffers. Which will cause worse predictions elsewhere (when this branch ip collides with a legitimate ip). Unless I missed a subtlety and never taken branches don’t get assigned any resources until they are taken (which would be pretty smart actually).
- gsnedders 7mo agoFrom when I was working on optimizing one or two things with Cython years ago, it wasn’t per-se the branch cost that hurt: it was impeding the compiler from various loop optimisations, potentially being the impediment from going all the way to auto-vectorisation.
- jaharios 7mo agojson.loads is something you don't want to use in a loop if you care for performance at all. Just simple using orjson can give you 3x speed without the need to change anything.
- antares0982 7mo ago[dead]
- elophanto_agent 7mo ago[dead]
- zahlman 7mo agoThe replacement of emdashes with double hyphens here is almost insulting. A look through the blog history suggests that the author has no issue writing in English normally, and nothing seems really off about the actual findings here (or even the speculation about causes etc.), so I really can't understand the motivation for LLM-generated prose. (The author's usual writing style appears to have some arguable LLM-isms, but they make a lot more sense in context and of course those patterns had to come from somewhere. The overall effect is quite different.) Edit: it's strange to get downvoted while also getting replies that agree with me and don't seem to object. (Also, I thought it wasn't supposed to be possible to edit after getting a reply?)
- adammarples 7mo agoSame problems, same Apple M4 Pro, real numbers.
- hydrolox 7mo agoYea while reading, I just didn't understand how you end up LLM writing the article? Clearly, the data and writeup are real. But, was it "edited" with an LLM? It looks closer to ~the entire thing being LLM written. I finished reading because the topic is interesting, but the LLM writing style is difficult to bear.. and I agree with your point that trying to fool us that it's human with `--` is just absurd
- LarsDu88 7mo agoI love how in an article about making python faster, the fastest option is to simply write Rust, lol
- falcor84 7mo agoThere's no surprise that Rust is faster to run, but I don't think there are many who would claim that Rust is faster to write.
- orochimaaru 7mo agoMaybe with LLM/Code Assistance this effort reduces? Since we're mostly talking mathematics here, you have well defined algorithms that don't need to be "vibed". The codegen, hopefully, is consistent.
- LarsDu88 7mo agoI actually started this comment thread, and I just "wrote" two things using Opus 4.6 in Rust: https://panel-panic.com https://panel-panic.com https://larsdu.github.io/Dippy6502/ https://larsdu.github.io/Dippy6502/ The issue is... I barely know the language. There are vast gaps in my knowledge (e.g. lifetimes, lifetime elison, dynamic dispatch, Box, Ref, Arc, all that) Nor do I know much of anything about the 6502 microprocessor. I know even less from having the LLM one shot most of the project rather than grinding through it myself. So in the age of AI, the question of how easy it is to write with a language may be less important than the question of how we should go about reading code. Quite honestly, I don't really know why I wouldn't use Rust for a wide variety of projects with AI other than the compile/iteration time for larger projects. The compiler and static typing provide tremendously useful feedback and guardrails for LLM based programming. The use of structs and traits rather than OOP prevent a lot of long term architectural disasters by design. Deployment on the web can be done with WASM. Performance is out-of-the-box? Writing Rust by hand though? I'm still terrible at it.
- scuff3d 7mo agoGo and Java/C# (if you forgo all the OOP nonsense) aren't much harder to write than Python, and you get far better performance. Not all the way to Rust level, bur close enough for most things with far less complexity.
- IshKebab 7mo agoInstead of just using a language that isn't dog slow, why not jump through these 5 different hoops? It's much easier!
- atomicnumber3 7mo agoBecause for 99% of cases python is fast enough and it's fast as fuck to code. And for the 1% that aren't, you have 50 different flavors of making it faster. And the final of which is "slap pybind on a c module to do the hot path in C" which then lets you minimize the suffering of C into a single high value location. And the rest of the code still gets to be Python.
- IshKebab 7mo ago> it's fast as fuck to code In my experience it's no faster than other better languages like Go, Rust or Kotlin. > And for the 1% that aren't, you have 50 different flavors of making it faster. Only for numerical code. You can't use something like Numpy to make Django or Mercurial faster. And even when you could feasibly do the thing that everyone says to do - move part of your code to a faster language - the FFI is so painful (it always is) that you are much better just doing everything in that faster language from the start. All of the effort you have to go through to make Python not slow is far less work than just "don't use Python". You can write Rust without thinking about performance and it will automatically be 20-200x faster than Python. I actually did rewrite a Python project 1:1 in Rust once and it was approximately 50x faster. I put no effort into optimising the Rust code.
- redgridtactical 7mo agoIn practice the ladder has two rungs for me. Write it in Python with numpy/scipy doing the heavy lifting, and if that's not enough, rewrite the hot path in C. The middle steps always felt like they added complexity without fully solving the problem. The JIT work kenjin4096 describes is really promising though. If the tracing JIT in 3.15 actually sticks, a lot of this ladder just goes away for common workloads.
- mathisfun123 7mo agothis is a pointless (valueless) reductive take
- bee_rider 7mo agoJax seems quite interesting even from this point of view… numpy has the same problem as blas basically, right? The limited interface. Eventually this leads to heresies like daxpby, and where does the madness stop once you’ve allowed that sort of thing? Better to create some sort of array language.
- redgridtactical 7mo agoJax basically gives you the array language without leaving Python, and the XLA backend means you're not hand-tuning C for the GPU path. The numpy interface limitation is real though and once you need something that doesn't map cleanly to vectorized ops, you're either fighting the abstraction or dropping down anyway. The daxpby example is a good one. Every time BLAS adds another special-case routine it's basically admitting the interface wasn't general enough. At some point you're just writing C with extra steps.
- viktorcode 7mo agoI was hoping for Mojo to appear as optimisation strategy
- intoXbox 7mo agoGreat write up and recognisable performance. For a pipeline with many (~50) build dependencies unfortunately switching interpreter or experimenting with free threading is not an easy route as long as packages are not available (which is completely understandable). I’m not one of these rewrite in Rust types, but some isolated jobs are just so well sorted for full control system programming that the rust delegation is worth the investment imo. Another part worth investigating for IO bound pipelines is different multiprocessing techniques. We recently got a boost from using ThreadPoolExecutor over standard multiprocessing, and careful profiling to identify which tasks are left hanging and best allocated its own worker. The price you pay though is shared memory, so no thread safety, which only works if your pipeline can be staggered
- alihawili 7mo agowhen dealing with JSON in cpython, I always use msgspec, performance gains is huge
- kristianp 7mo agonbody spectral-norm C 2100ms 400ms Graal 211ms 212ms PyPy 98ms 1065ms Seeing Graal and Pypy beat the gcc C versions suggests to me there's something wrong with the C version. Perhaps they need a -march=native or there's something else wrong. The C version would be a different implementation in the benchmark game, but usually they are highly optimised. Edit: looking at [1] the top C version uses x86 intrinsics, perhaps the article's writer had to find a slower implementation to have it running natively on his M4 Pro? It would be good to know which C version he used, there's a few at [1]. The N-body benchmark is one where they specify that the same algorithm must be used for all implementations. [1] https://benchmarksgame-team.pages.debian.net/benchmarksgame/performance/nbody.html https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
- mkoubaa 7mo agoThe language itself is not the issue, the implementations are wildly different in other ways
- kristianp 7mo agoThe nbody sim at least is forced to use the same algorithm. It seems unlikely that an optimised pypy (non-BLAS) implementation beats an optimised C imp by 20x.
- kristianp 7mo ago
- mwkaufma 7mo agoAll the approaches beyond PyPy are to either use a different lang that's superficially similar to python or to write a native extension for python in a different language, which is at odds with the stated premise.
- gcanyon 7mo agoPeople here on HN have in the past suggested that TypeScript is the superior-in-all-ways, just-as-easy/fun-to-code-in language and should replace Python in pretty much all use cases. Anyone have an opinion on how TS would fare in this comparison?
- 0xpgm 7mo agoAs a mostly Python programmer and partly TypeScript programmer, my subjective thought is that a bit more 'noise' with TypeScript than Python. Just a little more to parse with my eyes and a little more to type with TypeScript. But hey, with all these cool kids with their AI coding agents, reading and handwriting code may soon be obsolete!
- pjmlp 7mo agoTypescript is basically a JavaScript linter. The benefit is that JavaScript JIT compilers have a few decades of research behind them, all the way back to Smalltalk and SELF. So in many cases you can still stay with V8 or JavaScript Core, instead of rewriting into something else, regardless of the whole rewriting into Rust that is now fashionable.
- george_api_dev 7mo ago[dead]
- Trickery5837 7mo agoIt's missing the easiest of the choices: core performance-sensitive code in C, interface it to python with pybind11, build app in python. Small stack, huge gains, best of both worlds.
- blitzar 7mo agoIt's missing the easiest of the choices: grab a coffee and come back when it has run.
- gregjm 7mo ago> I don't know JAX well enough to explain exactly why it's 3x faster than NumPy on the same matrix multiplications. JAX is basically a frontend for the XLA compiler, as you note. The secret sauce is two insights - 1) if you have enough control, you can modify the layout of tensor computations and permute them so they don’t have to match that of the input program but have a more favorable memory access pattern; 2) most things are memory bound, so XLA creates fusion kernels that combine many computations together between memory accesses. I don’t know if the Apple BLAS library has fused kernels with GEMM + some output layer, but XLA is capable of writing GEMM fusions and might pick them if they autotune faster on given input/output shapes. > But I haven't verified that in detail. Might be time to learn. If you set the environment variable XLA_FLAGS=--dump_hlo_to=$DIRECTORY then you’ll find out! There will be a “custom-call” op if it’s dispatching to BLAS, otherwise it will have a “dot” op in the post-optimization XLA HLO for the module. See the docs: https://openxla.org/xla/hlo_dumps https://openxla.org/xla/hlo_dumps
- igouy 7mo ago> "The Benchmarks Game problems are pure compute: tight loops, no I/O, no data structures beyond arrays." iirc reverse-complement reads and writes a GB, fasta and mandelbrot write, regex-redux reads, k-nucleotide reads and uses a hash table. https://benchmarksgame-team.pages.debian.net/benchmarksgame/performance/comparable.html https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
- superbatfish 7mo agoWhen I read an article about Python optimizations, I typically expect to have significant objections. But this one was great, actually.