by Shish2k · 4y ago · 0 comments
zig: Emulated 600 frames in 0.24s (2521fps)
rs: Emulated 600 frames in 0.37s (1626fps)
cpp: Emulated 600 frames in 0.40s (1508fps)
nim: Emulated 600 frames in 0.44s (1367fps)
go: Emulated 600 frames in 1.75s (342fps)
php: Emulated 600 frames in 23.74s (25fps)
py: Emulated 600 frames in 26.16s (23fps) # PyPy
py: Emulated 600 frames in 33.10s (18fps) # 3.11
py: Emulated 600 frames in 61.43s (9fps) # 3.10
Doubling the speed is pretty nice :D Still the slowest out of all implementations though :P[0] https://github.com/shish/rosettaboy
EDIT> updated the nim compiler flags to build in release mode like most other languages, thanks @plainOldText!
nim: Emulated 600 frames in 0.44s (1367fps)
Do you happen to know the right flags for release-mode Go? Last time I checked (admittedly years ago) I thought they just had the one “reasonably fast and reasonably debuggable” build modePerhaps benchmarks should be compared on equal footing, say, with the default release flag or all optimizations turned on, otherwise they're improper.
I wonder what optimizations Zig does that lets it generate machine code / LLVM bitcode faster than both C++ and Rust (which certainly have larger teams backing them), at least in the case of this Gameboy emulator project.
[1] half the time I’d make the compiler crash; the other half it would generate a binary which crashes at runtime, with weird heisenbug behaviour like “adding a print statement to log how far down a function I am causes the code to stop crashing at all” — like right now there is a load-bearing print statement which shows the address of the SDL Window object, because otherwise the compiler seems to optimise the Window out of existence and then a few lines later it segfaults on the null pointer…
Is the most glorious thing I ever heard.
that sounds like you have undefined behavior in your program
https://stefan-marr.de/2022/10/cost-of-safety-in-java/
Unsafety buys you a little more performance, but the baseline should the safe version, not the unsafe version. It is like having to explain on a case by case basis why you aren't using lead pipes for this application.
Always default to safety. The difference between safe and unsafe native code is usually single digit percentage points. Or weeks on a Moore scale.
zig: Emulated 600 frames in 0.23s (2880fps)
rs: Emulated 600 frames in 0.35s (1691fps)
cpp: Emulated 600 frames in 0.40s (1519fps)
nim: Emulated 600 frames in 0.44s (1367fps)
go: Emulated 600 frames in 1.78s (338fps)
php: Emulated 600 frames in 9.28s (65fps)
py: Emulated 600 frames in 33.10s (18fps)
That's after Python cheated with native implementation of bitblt while all other implementations are doing it pixel by pixel, which is more correct.Applying BS scaling to the above table, Nim would score 1736, only slightly faster than the Rust. Who knows what little flag tweaks in cpp/rs/zig could similarly re-arrange the numbers?
Now, why is -d:lto (or -d:release) not the default build mode? Well, because it takes time and (some) people already complain about compile times and workflow (sometimes). Trade offs abound almost as much as over-conclusion. ;-)
PHP is traditionally used solely for websites. Some of those have grown rather large, to the point that having engineers optimize the language is cheaper than buying more servers.
Python, on the other hand, is first and foremost a scripting language. When performance does matter, you often end up using a wrapper around a C library, like NumPy. This means there is relatively little money in optimizing the Python interpreter.
It would seem sensible that since Facebook poured a lot of resources in optimizing PHP, Google would have done the same for Python.
Also, Python is the first or second most popular language.
Well they sort of half assed tried years ago - they employed GvR at one point. Then they gave up and they continue to lean heavily on C++, Java and there is thing they developed in the interim: Go.
> Also, Python is the first or second most popular language
Hogwash. For all the open source and other development that occurs and is “indexed” on internet discussion forums there is countless boring ass shit behind the scenes in sweatshops around the world and corporate back rooms. PHP, Java, and C# are still probably more popular to start.
By what metrics? Redmond quarterly from June shows Python at #2, and PHP at #4.
https://redmonk.com/sogrady/2022/10/20/language-rankings-6-2...
For Python, the C integration probably makes things harder.
In PHP, doing `$a->b` accesses field `b` of object `$a`. The implementation is essentially type check (making sure `$a` is an object) and hash table lookup. If this fails, then it calls `__get` method if it exists.
In Python on the other hand, `a.b` involves `__getattr__`, `__getattribute__`, `__mro__`, `__get__`, `__set__`, `__delete__` and `__dict__`. Here is a description of how the attribute access works: https://docs.python.org/3/howto/descriptor.html#overview-of-....
(Measures Python 3.10.4 against PHP 8.1.5 - so expecting these to change a bit).
It's generally faster than Python in doing the same things as Python does, unrelated to web too.
Meta/FB is also pretty invested in Hack (was once a php dialect, again, out of the loop), maybe they contributed a thing or two?
At Wikimedia we adopted it which has cut our CPU usage by half and has saved a few hundred of servers. We had some Facebook engineers helping which involved patching the Linux kernel while at it. Those were good times.
Eventually PHP 7 followed up with a similar approach and had more or less the same performance as HHVM. Facebook went then to focus on the Hack language (a dialect of PHP with strong typing) and eventually phased out back compat with Zend.
From what I remember, Sara Golemon at Facebook has done a lot of outreaching to Open Source project and gave us a lot of assistance (as well as others at Facebook).
I remember it being slower than PHP4 for a while
TIL MySQL 6
I recall a couple of times over the past 15-20 years where a current python significantly outperformed a current php version, but my recollection is that php was usually a bit faster, or sometimes a lot faster.
PHP 7 was released on dec 2015, and gained significant speed bumps and better memory usage, with the average php execution time being cut in half, or more, generally without any code change whatsoever. It was quite remarkable.
The path from 7.x-8.1 so far has generally seen incremental speed bumps again - usually somewhere between 3-8% improvements per release. Obviously this is going to be dependent on use cases, but overall it's been a fairly steady set of speed improvements over the last 7 years.
Of course, people then go and build up sculptures of objects that will be thrown away after every request, and that stuff makes everything slow (that style of code is why PHP wasn't good enough for Facebook, IMHO), but you can build trash sculpture in any language.
I'm also wondering if all your #[inline(always)] is slowing things down.
For the benchmark 600 frames, the Rust emulator calls it 2500049 times, but the Zig emulator only calls it 1808121 times. This is very roughly the ratio between the reported times.
At least one source of this discrepancy is that the Zig emulator doesn't think any sprites are active, but that doesn't account for all of it, and I'm hitting some crashes trying to run it with the display, so I'm probably not going to investigate it further.
(I also hit the same sort of strange Zig compiler unreliability as some other comments have mentioned, where I had to add some logging in seemingly random places to get the Zig emulator to run at all.
And the argument parser just blatantly returns a dead pointer to the ROM path; when I first ran it it just gave "error: InvalidUtf8" until I tracked that down.)
IIRC each of the #[inline] statements was tested and each made a noticable performance improvement. That’s especially true for things like RAM::get() - since the gameboy does I/O by having different chunks of RAM act differently (some address ranges are just RAM, some are hardware controls, some read data from the cartridge, etc) you can replace the hundred-line generic get() with a single instruction if you happen to know that you are looking up one hard-coded address, and that address has no special behaviour.
[1] https://mypyc.readthedocs.io/en/latest/introduction.html
--- a/py/src/cpu.py
+++ b/py/src/cpu.py
@@ -260,7 +260,6 @@ class CPU:
param = None
cmd_str = cmd.name
self.PC += 1
- self._debug_str = f"[{self.PC:04X}({ins:02X})]: {cmd_str}"says
# opcache in 8.1 gives a nice speedup (25s to 10s)
Is the 23.7 seconds above using the 8.1 opcache?
Unfortunately, "just write the performance-sensitive bits in C" is pretty impractical because it only works when you're handing the C routine a relatively small amount of data relative to the amount of work to be done on that data (otherwise the costs of marshaling to C data structures will quickly eat up any gains from processing in C). And unfortunately, it turns out that a whole bunch of code works this way, so the whole bargain of "slow interpreter + easy C extensions" breaks down for a lot of real-world applications, but now we're locked into it.
Processing loops adds a lot of overhead because the interpreter has to make the case jumps after each loop. Figuring out a way to minimize that overhead by using built-in data structures and stdlib library will speed up your code by an order of magnitude.
Don't forget, the built-in types are already running in C.
FFI can pervade an ecosystem making changes (including performance optimizations) to the host language more difficult. It also tends to complicate build and deployment stories. For example, from my Mac I can trivially build a native binary that will Just Work on any Linux system, even one without a libc. Contrast that with Python where I can’t even install popular packages onto most non-Ubuntu Linux distros. And there’s a lot of other things like that which crop up with pervasive FFI.
I’m convinced that the FFI sweet spot is “difficult but possible” and native performance should be good enough 99% of the time.
[profile.release]
lto = true
- With Zig I kept running into compiler bugs, plus no package manager (I’ve vendored SDL and Clap into the source tree)
- C++ I’d occasionally shoot myself in the foot in ways that other languages would have caught, plus no package manager (OS-level package management does an OK job, so long as you don’t mind using old versions, and faffing about with different operating systems acting very differently)
- The pain from Rust was one time where the compiler wanted me to specify a lifetime, and I didn’t understand, so I just spammed lifetime specifiers in various places until it compiled. I’ve been using Rust for a couple of years now and I still don’t really understand lifetimes, but thankfully 99% of the time I can avoid them.
- Nim was a relatively nice language but massively lacking in available libraries (like even parsing command line arguments took me a day just trying to find a library which worked)
- Go is pretty nice, my main pain is the tolerable but constantly-annoying verboseness of error handling (`err := foo(); if err != nil {return err}` compared to rust’s `foo()?`)
- PHP I just hate on a deep and personal level thanks to years of being a PHP4/5 developer. The language is actually mostly-ok-ish these days, but the standard library is still full of frustration like inconsistent parameter orders within a family of functions.
- Python is all-round really nice to write, but the test suite takes like 20 minutes to run, which really messes with my flow-state
" I’ve been using Rust for a couple of years now and I still don’t really understand lifetimes"
Seems like a major pain point.
I ran a quick pprof and indeed it's spending a lot of time in cgo:
Showing nodes accounting for 28720ms, 67.67% of 42440ms total
Dropped 145 nodes (cum <= 212.20ms)
Showing top 10 nodes out of 53
flat flat% sum% cum cum%
13080ms 30.82% 30.82% 16600ms 39.11% runtime.cgocall
4720ms 11.12% 41.94% 4750ms 11.19% main.(*RAM).get
2840ms 6.69% 48.63% 33070ms 77.92% main.(*GPU).tick
1970ms 4.64% 53.28% 3720ms 8.77% runtime.mallocgc
1450ms 3.42% 56.69% 1470ms 3.46% main.(*RAM).set
1160ms 2.73% 59.43% 41350ms 97.43% main.(*GameBoy).tick
1000ms 2.36% 61.78% 3160ms 7.45% runtime.exitsyscall
890ms 2.10% 63.88% 1610ms 3.79% main.(*CPU).tick_interrupts
820ms 1.93% 65.81% 850ms 2.00% runtime.casgstatus
790ms 1.86% 67.67% 5530ms 13.03% main.(*CPU).tickThe other languages are also using SDL via their respective interacting-with-C interfaces - what makes Go special here?
https://stackoverflow.com/questions/28272285/why-cgos-perfor...
Even if it is SDL slowing it down, Go FFI being slow is still a real disadvantage compared to the other languages, and you can't just pretend like it doesn't exist in this case.
By these standards a 10 year old cpu with a beefy GPU will beat any new cpu as well.
It absolutely does. A simple for loop in the standard Python interpreter will literally take 100x longer than the same thing in a language like C/C++, try for yourself if you don't believe me. CPython is unbelievably slow.
$ brew install pypy3
pypy3: The x86_64 architecture is required for this software.$ pyenv install pypy3.9-7.3.9
I like using PyEnv for managing my Python versions. It will natively compile Python builds and should be doing the same on M1 (which is what I'm using). `pyenv install --list` shows you what is available.
EDIT: Not sure why they don't have newer versions of PyPy there (I don't use PyPy) but all it takes is a PR to here: https://github.com/pyenv/pyenv
ED> Looks like CPython prefers using a dict as a lookup table for opcodes (which is what this implementation does), while PyPy prefers having a long series of if-statements. Hmm.
Best wishes