In the book "On Lisp" written by Paul Graham, he says lisp can be fast as C, this surprised me. So I decide to benchmark them.
The Lisp code is from his book:
(proclaim '(optimize speed))
(defun triangle (n)
(labels ((tri (c n)
(declare (type fixnum n c))
(if (zerop n)
c
(tri (the fixnum (+ n c))
(the fixnum (- n 1))))))
(tri 0 n)))
Run it:
CL-USER> (time (triangle 1734567890))
Evaluation took:
2.908 seconds of real time
2.924000 seconds of total run time (2.924000 user, 0.000000 system)
100.55% CPU
7,537,146,462 processor cycles
43,216 bytes consed
1504362883376809995
The C code is written by me:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
long int sum = 0;
long int up = atol(argv[1]);
printf("triangle %ld\n", up);
clock_t t = clock();
for (int n = 0; n < up; sum += ++n)
;
t = clock() - t;
printf("sum: %ld\n", sum);
printf("clicks: %d, seconds: %f\n", t, ((float)t) / CLOCKS_PER_SEC);
return 0;
}
Compile and run:
$ gcc -std=c11 triangle.c && ./a.out 1734567890
triangle 1734567890
sum: 1504362883376809995
clicks: 3909479, seconds: 3.909479
Amazing! Lisp is faster than C by 34.4% = ( 3.909 / 2.908 - 1 ). Unbelievable!
But then I forgot that I did not use gcc to optimize the C code. Use -O3:
$ gcc -O3 -std=c11 triangle.c && ./a.out 1734567890
triangle 1734567890
sum: 1504362883376809995
clicks: 584493, seconds: 0.584493
This times, C is faster than lisp by 397.9% = ( 2.908 / 0.584 - 1).
Conclusion:
Lisp is faster than not optimized C, but slower than fully optimized C.