OCaml 微基准测试
我正在尝试对 c 和 ocaml 进行基本的微基准比较。我听说对于斐波那契程序,c 和 ocaml 大致相同,但我无法复制这些结果。我使用 gcc -O3 fib.c -o c-code 编译 c 代码,并使用 ocamlopt -o ocaml-code fibo.ml 编译 OCaml 代码。我使用 time ./c-code 和 time ./ocaml-code 进行计时。每次我执行此操作时,OCaml 都会花费 0.10 秒,而 c 代码每次大约需要 0.03 秒。除了这是一个简单的基准测试之外,还有没有办法让 ocaml 更快?谁能看到他们计算机上的时间吗?
奥卡米尔
#include <stdio.h>
int fibonacci(int n)
{
return n<3 ? 1 : fibonacci(n-1) + fibonacci(n-2);
}
int main(void)
{
printf("%d", fibonacci(34));
return 0;
}
let rec fibonacci n = if n < 3 then 1 else fibonacci(n-1) + fibonacci(n-2);;
print_int(fibonacci 34);;
I am trying a basic microbenchmark comparison of c with ocaml. I have heard that for the fibonacci program, c and ocaml are about the same, but I can't replicate those results. I compile the c code with gcc -O3 fib.c -o c-code, and compile the OCaml code with ocamlopt -o ocaml-code fibo.ml. I am timing by using time ./c-code and time ./ocaml-code. Every time I do this OCaml takes 0.10 seconds whereas the c code is about .03 seconds each time. Besides the fact that this is a naive benchmark, is there a way to make ocaml faster? Can anyone see what the times on their computers are?
C
#include <stdio.h>
int fibonacci(int n)
{
return n<3 ? 1 : fibonacci(n-1) + fibonacci(n-2);
}
int main(void)
{
printf("%d", fibonacci(34));
return 0;
}
OCaml
let rec fibonacci n = if n < 3 then 1 else fibonacci(n-1) + fibonacci(n-2);;
print_int(fibonacci 34);;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当使用 gcc -O2 编译时,ML 版本已经击败了 C 版本,我认为这是一个相当不错的工作。查看 gcc -O3 生成的程序集,看起来 gcc 正在执行一些积极的内联和循环展开。为了使代码更快,我认为您必须重写代码,但您应该专注于更高级别的抽象。
The ML version already beats the C version when compiled with
gcc -O2
, which I think is a pretty decent job. Looking at the assembly generated bygcc -O3
, it looks likegcc
is doing some aggressive inlining and loop unrolling. To make the code faster, I think you would have to rewrite the code, but you should focus on higher level abstraction instead.我认为这只是 ocaml 的开销,与更大的程序相比会更有意义。
您可以使用
-S
选项生成汇编输出,并使用-verbose
来查看 ocaml 如何调用外部应用程序 (gcc
)。此外,使用-p
选项并通过gprof
运行应用程序将有助于确定这是否是ocaml
的开销,或者您实际上可以做的事情提升。干杯。
对于我的计算机,我得到以下信息,
I think this is just an overhead to ocaml, it would be more relevant to compare with a larger program.
You can use the
-S
option to produce assembly output, along with-verbose
to see how ocaml calls external applications (gcc
). Additionally, using the-p
option and running your application throughgprof
will help determine if this is an overhead fromocaml
, or something you can actually improve.Cheers.
For my computer I get the following,