Speed comparison between C & Lisp

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值