如果有的话,如何改善Clojure的数值性能?

时间:2018-10-02 02:50:28

标签: performance clojure

这是一个简短的Scala程序,它通过生成一堆随机数来计算欧拉数的近似值:

package example

import scala.util.Random

object ApproxE extends App {

   def calc = {
     var S = 0.0
     for {i <- 1 to 100000000} {
       var x = 0.0
       var t = 0
       while (x <= 1.0) {
         x += Random.nextDouble
         t += 1
       }
       S += t
     }
     S / 100000000
  }

  val st = System.currentTimeMillis()
  val e = calc
  val ed = System.currentTimeMillis()

  println(e)
  println(ed - st)

}

在笔记本电脑上运行,它可以在大约7秒钟内完成计算。

以下是两个等效的Clojure函数。开启会在48秒内返回,另一个会在230秒内返回。

是否可以用纯Clojure编写具有与Java或Scala相同的性能的等效程序?

48s:

(defn calc []
    (loop [i (int 0)
           S (double 0.0)]
        (if (= i 100000000)
            (/ S 100000000)
            (let [rs (repeatedly rand)
                  ps (reductions + rs)
                  <=1 #(<= % 1)]
              (->> ps
                (take-while <=1)
                (count)
                (inc)
                (+ S)
                (recur (inc i)))))))

230s:

(defn calc2 []
    (with-local-vars [S 0.0]
        (dotimes [i 100000000]
            (with-local-vars [x (double 0)
                              t (int 0)]
                (while (<= @x 1)
                    (var-set x (+ @x (rand)))
                    (var-set t (inc @t)))
                (var-set S (+ @S @t))))
        (/ @S 100000000)))

1 个答案:

答案 0 :(得分:7)

由于分配,惰性数据结构和局部var都会增加开销(尽管您仍然可以通过将xt的分配移出循环来使带有var的变体更快),名称解析(对于vars)和方法调用。

Scala代码的逐字翻译将使用本地绑定(使用letloop),这些绑定等效于Java的本地变量:

(defn calc-loops []
  (loop [i (int 0)
         S (double 0.0)]
    (if (= i 100000000)
        (/ S 100000000)
        (recur
         (inc i)
         (loop [t 0 x 0.0]
           (if (<= x 1.0)
             (recur (inc t) (+ x (rand)))
             (+ S t)))))))

(time (calc))       ;; => "Elapsed time: 56255.692677 msecs"
(time (calc-loops)) ;; => "Elapsed time: 8800.746127 msecs"