为什么这个Clojure程序这么慢?如何使它运行快? [英] Why is this Clojure program so slow? How to make it run fast?
问题描述
这里清楚地解释了如何优化Clojure程序处理原始值:使用类型注释和未检查的数学,它会运行快速:
Here it is clearly explained how to optimize a Clojure program dealing with primitive values: use type annotations and unchecked math, and it will run fast:
(set! *unchecked-math* true)
(defn add-up ^long [^long n]
(loop [n n i 0 sum 0]
(if (< n i)
sum
(recur n (inc i) (+ i sum)))))
好奇心,我试过在 lein repl
,令我惊讶的是,发现这个代码运行慢约20倍的预期(Clojure 1.6.0在Oracle JDK 1.8.0_11 x64):
So, just out of curiosity, I've tried it in lein repl
and, to my surprise, found this code running ~20 times slower that expected (Clojure 1.6.0 on Oracle JDK 1.8.0_11 x64):
user=> (time (add-up 1e8))
"Elapsed time: 2719.188432 msecs"
5000000050000000
$ b b
Scala 2.10.4(相同JVM)中的等效代码在〜90ms内运行:
Equivalent code in Scala 2.10.4 (same JVM) runs in ~90ms:
def addup(n: Long) = {
@annotation.tailrec def sum(s: Long, i: Long): Long =
if (i == 0) s else sum(s + i, i - 1)
sum(0, n)
}
Clojure代码示例?为什么它这么慢(理论上应该大致相同的速度)?
So, what am I missing in the Clojure code sample? Why is it so slow (should theoretically be roughly the same speed)?
推荐答案
用
通常是一个坏主意,因为它专门设置非服务器JVM设置。直接使用Clojure JAR我在一个3.5GHz的i7 iMac上看到〜40ms,在OS X 10.9下运行JDK 8.
Benchmarking with lein repl
is generally a bad idea as it specifically sets non-server JVM settings. Using the Clojure JAR directly I see ~40ms on a 3.5ghz i7 iMac running JDK 8 under OS X 10.9.
这篇关于为什么这个Clojure程序这么慢?如何使它运行快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!