gpt4 book ai didi

c - OCaml 微基准测试

转载 作者:行者123 更新时间:2023-12-04 12:15:32 27 4
gpt4 key购买 nike

我正在尝试对 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 更快?谁能看到他们计算机上的时间是多少?

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;
}

OCam

let rec fibonacci n = if n < 3 then 1 else fibonacci(n-1) + fibonacci(n-2);;
print_int(fibonacci 34);;

最佳答案

当使用 gcc -O2 编译时,ML 版本已经击败了 C 版本,我认为这是一个相当不错的工作。查看由 gcc -O3 生成的程序集,看起来 gcc 正在执行一些激进的内联和循环展开。为了使代码更快,我认为您必须重写代码,但您应该专注于更高级别的抽象。

关于c - OCaml 微基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com