Benchmarking for fun ...
Summary
This is about my hobby and profession, computer programming. And my latest findings are that SQLite3 is a very fast database and NodeJS is ready for serious number crunching.
Background
My first programming task was to find if a given number is a prime number or a composite. I think it was on a CompuCorp 425. I've since then written that program on many calculators, mostly Hewlett Packard, and in various languages like Assembler, Awk, Basic, Bash (!!!), C, C++, Fortran, Java, JavaScript, Lua, NodeJS, REXX, Pascal, Perl, PostScript, Python and some forgotten ones, I'll have to dig through my subversion repository for the full list. (Not Lisp, APL or COBOL yet ...)
That program, written in the early 70's, has evolved into an unscientific benchmark. The algorithm is called Trial Divisor Improved. It's not the fastest, but it's simple. See below.
This last week I reran the tests and decided to add SQL. So I wrote a wrapper for my C code and added it to SQLite3. The result was very surprising ...
The time it takes to find all primes < 10 millions varies from some seconds to half a day depending on your language and HW. Details below.
The result
~ 2.5 seconds : C / C++ is always faster as long as you stick to 32 bit integers
~ 3 seconds : Fortran 95
~ 4 seconds : NodeJS / JavaScript is very fast, this is a big surprise to me
~ 6 seconds : C/ C++ with 64 bit integers
~ 10 seconds : SQLite3 with ISPRIME() added with 64 bit integers. Wow!
This is very close to native C / C++ with 64 bit integer. There is a lot of overhead in writing SQL I even had to do a short loop in Bash to complete the benchmark, still it's mindblowing fast.
Hardware
All these tests where run on a virtual 64-bit Ubuntu 18.04.1 LTS with a single core Intel(R) Core(TM) i5-4260U CPU @ 1.40GHz and 256 MB RAM on a Macbook Air (Early 2014).
The algorithm
How test if x is a prime number:
for n in (2,3,5,7) : if( x == p ) return true; if( x % n == 0 ) return false;
n=7; while( n*n <= x ) { for inc in (4,2,4,2,4,6,2,6) { n = n+inc; if( x % n == 0 ) return false;} } return true;
I wrote a Lisp (Common Lisp) version, download SBCL (Steel Bank Common Lisp) and tell me how does it go: https://gist.github.com/defunkydrummer/14da872dc3b8805db134a83ee247054e Edit: Updated version, 28-02-2019, with massive speedup.