目前我正在赶上Haskell,到目前为止我印象非常深刻.作为一个超级简单的测试,我写了一个程序,计算总和直到十亿.为了避免列表创建,我编写了一个应该是尾递归的函数
summation start upto
| upto == 0 = start
| otherwise = summation (start+upto) (upto-1)
main = print $ summation 0 1000000000
Run Code Online (Sandbox Code Playgroud)
用-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;
}
Run Code Online (Sandbox Code Playgroud)
使用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 …Run Code Online (Sandbox Code Playgroud)