Clojure在简单循环和Java上的表现真的很糟糕
2022-09-01 10:35:02
剧透预警,这是欧拉计划的第5个问题。
我试图学习Clojure并解决了问题5,但它慢了几个数量级(Java中的1515 ms与Clojure中的169932 ms)。我甚至尝试使用类型提示,未经检查的数学运算和内联函数都为零。
为什么我的Clojure代码要慢得多?
Clojure code:
(set! *unchecked-math* true)
(defn divides? [^long number ^long divisor] (zero? (mod number divisor)))
(defn has-all-divisors [divisors ^long num]
(if (every? (fn [i] (divides? num i)) divisors) num false))
(time (prn (some (fn [^long i] (has-all-divisors (range 2 20) i)) (iterate inc 1))))
Java 代码:
public class Problem5 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
int i = 1;
while(!hasAllDivisors(i, 2, 20)) {
i++;
}
long end = System.currentTimeMillis();
System.out.println(i);
System.out.println("Elapsed time " + (end - start));
}
public static boolean hasAllDivisors(int num, int startDivisor, int stopDivisor) {
for(int divisor=startDivisor; divisor<=stopDivisor; divisor++) {
if(!divides(num, divisor)) return false;
}
return true;
}
public static boolean divides(int num, int divisor) {
return num % divisor == 0;
}
}