CUPC/8: sim.py -> sim.nim

So the (Python3) simulator is slllooowwwww (Kernel running at ~400KHz) and I decided to see whether there was some easy way to rectify the situation. Ultimately I'm simulating a very simple 8-bit RISC-based machine - albeit SPI-transaction-heavy for the display - and 400KHz on my 3GHz Haswell i5 is simply abysmal!

Unrelated to this issue, a few weeks ago I chanced across some discussions extolling and debating the virtues of some 'modern' languages. Having given Go[lang] a 'go' in the past - and disliking the experience immensly - I wondered if there was anything else out there that I could learn as I do enjoy learning new languages from time-to-time. And that's when I came across Nim.

What caught my eye was that is was being sold as a 'Python-like' language in respect to syntax and ease-of-use which generated Native code. Furthermore, its killer feature in my opinion is its ability to evaluate user functions at compile time and optimize accordingly.

To cut a long story short, I decided to re-implement the simulator in Nim, both as a way to learn the language and to see whether it would improve performance.

As a disclaimer: I don't yet know much Nim and my code is rubbish (e.g. I couldn't work out how to get a function-lookup hashtable working so I just went for the good ol' case-statement route for now). I basically just wrote it like i write Python and it mostly worked out okay.

At some point last night, the simulator's Nim-rewrite reached feature-parity (sans command line options) with the Python implementation (as of now depricated).

Kernel test executing on Nim simulator

I'm pretty happy with how this exercise worked out. The results are fantastic! The same kernel code is running on the nim-based (and hence native code) simulator (sim.nim, simdisplay.nim) about a factor of 10X better than the Python one! 3.5-4MHz is more like it! It's still around 10X-20X worse than the hardware should be but good enough for what I'm simulating at the moment. I can potentially eek out some more performance from it by writing code like a normal person and perhaps using an openGL-accelerated surface for the display; but that's an exercise for another time!

Nim is a great language and is a good demonstration of why Python isn't always 'good enough'. Highly recommended.