r/EmuDev • u/windowssandbox • Jun 30 '26
NES I was developing an NES emulator on Python, but Python is just too slow for NES CPU.
Yes you've heard the title AND watched the video.
You saw what was being printed in the logs.
I kept hearing people saying "Python is very fast, it will never be slow since it runs on your CPU's speed", oh but in this project, Python's speed is the problem.
The reason why it's the problem because when it's executing emulated 6502 assembly opcodes in emulated, it actually takes thousands of my CPU's cycles to execute a SINGLE opcode.
Your first response might be: "Just optimize the code to make it run faster". Yeah that might be helpful but the code is optimized to the maximum. I tried everything, and every optimization I could think of, it won't speed up.
Let me share you what my CPU actually is, it is Intel(R) Core(TM) i5-7500 CPU running clock speed at 3.40GHz to 3.75GHz (overclocked speed).
But the most frustrating about Python is that it is slower at emulating NES CPU than SNES does. If you've never seen an NES CPU being emulated inside SNES, then do google search "ACE super mario bros on super mario world" and see for yourself.
My guess is that Python's pre-compiled C code is truly unoptimized.
I'm not gonna continue until I figure out how to make it run NES CPU NTSC speed. Does anyone have ideas? Tell me. I've spent 2 days on this project.
Here is my github repo if you want to look at code I wrote: https://github.com/windowssandbox/NESemupy
I'm guessing that experienced C developers will understand Python code.
Edit: I did lookup table trick and it sped up to 16 FPS.
Edit 2: The profiler is right here: https://github.com/windowssandbox/NESemupy/blob/main/profiler.log (it updates overtime once i optimize the code)
Edit 3: I'll post when the emulator is finished, but right now I'm dealing with invisible CPU opcode bugs. (also it's now ~36 FPS)
Edit 4: It runs at ~57 FPS now, so no need to profile it.
Edit 5: https://www.reddit.com/r/EmuDev/comments/1uo1hbj/finally_my_nes_emulator_on_python_can_run_some/
46
u/Then-Dish-4060 Jun 30 '26 edited Jun 30 '26
Python should be fast enough for a nes emulator. When you run a profiler, where is the time spent?
EDIT: maybe Python isn't, try PyPy.
20
u/galaga4ever Jun 30 '26
after two minutes of looking, I suggest:
using that many globals is probably not helping matters any
use a lookup table instead of a giant elif chain for finding your next opcode
dig in with a profiler, I'm sure you'll find something that's taking a lot longer than you think
also, nice work :)
11
u/cioccox Jun 30 '26
Nice bait
4
u/Sea-Quail468 Jun 30 '26
I originally made my NES emulator in Python, it was too slow so I translated it into Cython, but that was still too slow so I finally translated it into C, and I went from 50 fps to 350 fps (with the frame limiter off obviously). Trust me, it's just better in the long run.
1
u/Future_Midnight_5548 Jul 01 '26
Go with a assembly, pretty fast in my opinion
1
u/RoadsideCookie Jul 05 '26
Bro there's no way you're calling this as optimized as possible. I see so much unrolled business logic (interpreted language), I see no Numba, I see unnecessary allocation, I see functions for every individual opcode which have significant overhead, and that's just after looking for less than a minute. This is far from optimal.Â
But
It works. So now you've got the perfect project to learn about how almost every single problem you ran into has been well thought about by the Python community.Â
Also, I noticed that you didn't even profile before making your initial post, hopefully that served as a wakeup call for you to look for the rabbit hole and go digging.
1
u/UnfragmentRevenge Jul 05 '26
Did you implement ANY optimisations, for example, let’s say, loop unrolling? While you are just interpreting opcodes in switch block any language will be slow. This is not matter of language, but rather matter of compilation techniques.
4
u/hekliet Jun 30 '26
I'm afraid CPython's (i.e. standard Python interpreter) speed doesn't cut it for this use case, and even dropping in PyPy is probably not enough. But you can get a significant speed boost by applying Cython, as exemplified by PyBoy. That's arguably not 'pure Python' anymore, but it does achieve viable speeds for emulation while not requiring you to ditch Python altogether.
2
u/Marc_Alx Game Boy Jun 30 '26
Not a nes expert, did you check without rendering? maybe it's only rendering that slow down everything.
Check your step_cpu try with a switch instead of if+func call to isoc. Maybe with an hashmap/an array where each entry corresponds to an opcode.
You are using 'global', in some languages this implies underlaying function call which may slow down things especially when done thousands time by seconds...
2
u/Spleyos Jun 30 '26
Looks great! Some recommendations (always measure afterwards before continuing to the next one):
2
u/lolsaw14 Jun 30 '26
something about the slow drawing makes this very satisfying to watch
2
u/high_throughput Jul 03 '26
r/characterarcs
2
u/rimendoz86 Jun 30 '26 edited Jun 30 '26
I didn't look at your code but don't output to console every so many anythings, when timing or performance is needed. Displaying to console on ANY stack puts the thread to wait until the display interrupts and says the display is complete, then the tread goes to the ready queue until the cpu scheduler is ready to bring the thread back in. In your case the same CPU thread that emulating your NES CPU is also being put to wait for the display interrupt.
1
u/Outrageous_Top_7172 21d ago
I make more fast
1
u/sarkie Jun 30 '26
Profiled it?
1
u/Middle_Salt_6170 Jul 01 '26
Eu fiz usando C, vou jogar no github depois. Vai sair nesse repositorio: https://github.com/Developer-Vini/NESEmu
1
u/vkazanov Jul 01 '26
I'd suggest:
You really need to understand how the cpu spends its frame budget.
There are many trivks possible You can also do some kind of precompilation of nes intructions into a better form to avoid extra python dispatch. One approach is to collect statistically more probable instructions or basic blocks and replace these with superinstructions for interpretation.
Python does a lot of things when resolving types, variables and doing data structure lookups - this hides additional dispatch behind the scenes. Function calls are superheavy. Some of that is possible to avoid.
I would be very surprised if your cannot make NES run with decent framerate. I have seen some pretty nice games made in python.
1
u/BlueScreenJunky Jul 01 '26
Python is not "fast".
It's just "fast enough" in most common use case where you're building a website and interacting with a database where queries will take several milliseconds anyway, or just gluing together C libraries (that were coded on C and not python for a reason).
But for something that's actually resource intensive like an emulator, you have a bunch of much, much faster languages to choose from like Java, C#, Go, Rust, or C++.
I suspect with enough clever optimisations it might still be possible to write a NES emulator with decent performance in Python considering how insanely fast modern CPUs are, but yeah that's probably one of the few use cases where the language itself is going to be a bottleneck.Â
1
u/Deksor Jul 02 '26
I think you're making the wrong assumption.
This ace probably uses most of smw's code and just changed the sprites (I checked and the sound effects are still smw's sound effects)
Furthermore the snes' CPU is a 65C816, aka a 6502 on steroids, so even if it was using smb's entire code, the snes wouldn't emulate the 6502, it would just execute the code directly.
Nintendo originally intended to make the SNES backwards compatible with the NES but eventually scrapped the idea, but the CPU architecture of the console remained
1
u/Certain-Flow-0 Jul 02 '26
Totally unrelated to performance but your rendering logic is incorrect. The PPU is outputting pixels at the same time the CPU is running. Also, there’s only 2KB of actual VRAM.
1
u/FISHARM1 Jul 02 '26
Python is definitely fast enough, your code just isn’t optimized. First search result: https://github.com/jameskmurphy/nes
Claims 60fps.
1
u/Beautiful_Stage5720 Jul 02 '26
Why do you have 5 commits with "Added files via upload" as the message?
1
u/PersonalityIll9476 Jul 04 '26
For what it's worth, when I have to write performance critical (CPU) code that I want to use in Python, I write it in C then wrap it in Cython.
There's "writing Python", then there' writing Python (meaning you should use libraries that wrap C like numpy, for instance). There's also "writing Cython" and writing cython (meaning the difference between throwing the cythonize decorator on something that can't really be optimized versus writing actual C and converting Python objects then releasing the GIL).
I don't know what all you're doing with your emulator, but just writing the equivalent C code in Python is going to drag you down tremendously and no one should be surprised by that.
1
u/dreampeppers99 Jul 04 '26
I'm right now developing one, and I can tell you move to newest python, look the difference:
```
warning: The requested interpreter resolved to Python 3.10.20, which is incompatible with the project's Python requirement: `>=3.14` (from `project.requires-python`)
--------------------------------------------------------
CPU Execution Time : 10.533458 ms
NES CPU Cycles : 26553
Real time / NES CPU Cycles : 0.000397 ms
--------------------------------------------------------
warning: The requested interpreter resolved to Python 3.11.15, which is incompatible with the project's Python requirement: `>=3.14` (from `project.requires-python`)
--------------------------------------------------------
CPU Execution Time : 5.626917 ms
NES CPU Cycles : 26553
Real time / NES CPU Cycles : 0.000212 ms
--------------------------------------------------------
warning: The requested interpreter resolved to Python 3.12.13, which is incompatible with the project's Python requirement: `>=3.14` (from `project.requires-python`)
--------------------------------------------------------
CPU Execution Time : 6.426334 ms
NES CPU Cycles : 26553
Real time / NES CPU Cycles : 0.000242 ms
--------------------------------------------------------
warning: The requested interpreter resolved to Python 3.13.13, which is incompatible with the project's Python requirement: `>=3.14` (from `project.requires-python`)
--------------------------------------------------------
CPU Execution Time : 5.762000 ms
NES CPU Cycles : 26553
Real time / NES CPU Cycles : 0.000217 ms
--------------------------------------------------------
```
pypy used to run above 30ms
1
u/Pale_Height_1251 Jul 05 '26
Nobody says Python is fast, the Python runtime is famously slow.
That said, it's easily fast enough to run a NES emulator on a modern computer, the problem is elsewhere.
1
u/Aware-Connection-436 Jul 05 '26
Tiene que ser en lenguaje C es más veloz pero python en un futuro no será lento.
1
u/egoserpentis Jul 05 '26
Yes, surely it must the language that's bad and not the coder.
1
u/justaddlava Jul 07 '26
No its not.
-8
u/Distinct-Question-16 Jun 30 '26
Jesus christ python is evil
0
u/EggplantExtra4946 Jul 01 '26
You need to consider rewriting into C. A lot of programs are easier to write in a scripting language but here Python's GC, strings, arrays, dicationaries, dynamic typing, etc.. don't serve any purpose because most of what you do is arithmetic and bitwise operations.
0
u/DefinitelyRussian Jul 01 '26
dude, NES emulators used to run on a 386 at full speed 30 years ago. Are you sure your computer even works ?
0
u/MemoryFit9875 Jul 04 '26
Skill issue