【发布时间】:2016-01-27 02:03:52
【问题描述】:
目前我正在追赶 Haskell,到目前为止我印象非常深刻。作为一个超级简单的测试,我编写了一个程序来计算总和到十亿。为了避免创建列表,我写了一个应该是尾递归的函数
summation start upto
| upto == 0 = start
| otherwise = summation (start+upto) (upto-1)
main = print $ summation 0 1000000000
使用 -O2 运行它,我的机器上的运行时间约为 20 秒,这让我很惊讶,因为我认为编译器会更加优化。作为比较,我写了一个简单的 c++ 程序
#include <iostream>
int main(int argc, char *argv[]) {
long long result = 0;
int upto = 1000000000;
for (int i = 0; i < upto; i++) {
result += i;
}
std::cout << result << std::end;
return 0;
}
在没有优化的情况下使用 clang++ 编译运行时间约为 3 秒。所以我想知道为什么我的 Haskell 解决方案这么慢。有人有想法吗?
在 OSX 上:
clang++ --version:
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.2.0
Thread model: posix
ghc --version:
The Glorious Glasgow Haskell Compilation System, version 7.10.3
【问题讨论】:
-
值得注意的是,它是不必要的。我意识到这可能是对递归等的简单测试,但欧拉的三角数公式在这里是相关的。我们不要忘记,简单的数学运算比其他方法要快得多。
-
另外,你的
start变量被误导了 -
默认为任意精度算术。这总是比 32 位算法慢。
标签: performance haskell