Python CPU benchmark / prime number cruncher

2023-08-09

I've never actually written any Python before. So I decided it was time. Talk about late to the game...

So I made a small CPU benchmark prime cruncher / test tool. It's basically a port of my C version that I made way back when I was first trying out C. Spoiler alert — The Python version is much slower than the C version ;-) But I very much enjoy the language. Easy to get started, has a lot of libraries, and therefore lets you get stuff done really fast. Who doesn't like productivity? (Indentation-based scoping will take some getting used to)

I first used "classic" threads from the threading module, but quickly realized that every thread you spawn runs on a single CPU core (Thanks to the GIL - Global Interpreter Lock). That didn't perform too well let me tell ya'. So I resorted to using separate processes for crunching prime numbers using the Process class from the multiprocessing module/library. That worked out much better and all my CPU cores lit up. It still turned out to be about 20x slower than the C implementation, but that's expected I suppose since Python is an interpreted language. I also tried using pypy (pypy3) just for fun. That was significantly faster — about 10x faster than running it with python3. Still a lot slower than the C version though.

All in all, a fun little experiment. I'll hopefully be using Python more in the future.

The project is on GitHub


Tags:python,pypy,cpu,benchmark,bench,prime,number,crunch,cruncher,concurrency,multiprocessing,multi,core,threads,gil

Home