clojure amap很慢

时间:2013-10-05 19:57:36

标签: arrays performance clojure

所以我一直在做clojure中的基本图像处理(只是将rgb转换为灰度),而且我遇到了amap的严重问题;也就是说,我不能快速做到。

我已经能够通过类型提示将它从21000ms降低到大约8000ms,但这就是它。相比之下,法线贴图在大约400ms内运行......

我还能做些什么来使它像这样的简单操作一样快?

(defn setpxl [^BufferedImage image data]
  (let [h (.getHeight image)
    w (.getWidth image)]
  (.setRGB image 0 0 w h ^ints data 0 w)
) )

(defn getrgb [rgb]
 (let [r  (bit-shift-right (bit-and rgb (int 0x00FF0000)) 16)
    g  (bit-shift-right (bit-and rgb (int 0x0000FF00)) 8)
    b  (bit-and rgb (int 0x000000FF))]
[r g b])
)

(defn graycalc [[r g b]]
  (let [gray (int (/ (+ r g b) 3))
    r  (bit-shift-left gray 16)
    g  (bit-shift-left gray 8)
    b  gray
    a  (bit-shift-left 0x00 24)
    ]
  (int (bit-or a r g b))))

(defn testrgb []
  (let [img (time (javax.imageio.ImageIO/read (as-file "D:/cat.jpg")))
    h (.getHeight img)
    w (.getWidth img)
    arr (time (int-array (getpxl img)))
    gray (time
          ;;why is amap so slow?

          ;;400ms
          (int-array (map #(graycalc (getrgb %1)) arr))

          ;;8000ms
          ;; (amap ^ints arr idx ret (graycalc (getrgb (aget ^ints arr idx))))
          )

    frame (JFrame. "grayscale image")
    label (JLabel. (ImageIcon. img))
    panel (.getContentPane frame)]

(-> panel (.add label))
(.setSize frame w h)
(.setVisible frame true)

(time (setpxl img gray))
(.repaint panel)
)

1 个答案:

答案 0 :(得分:3)

我必须添加一些代码才能运行您的示例,因此这里的结果是gist

不知何故,我觉得反思正在进行,因为aget需要一些帮助来获得全速的类型。这是一个相关的SO thread

使用:

 (set! *warn-on-reflection* true)

回来了:

 Reflection warning, core.clj:46:11 - call to aset can't be resolved.

加载文件时。

事实证明,每个像素上使用的函数都缺少返回类型。我们可以通过转到:

将类型添加到您的代码中
 (amap ^ints arr idx ret (graycalc (getrgb (aget ^ints arr idx))))

成:

 (amap ^ints arr idx ret ^int (graycalc (getrgb (aget ^ints arr idx))))

aset用于数组的每个值,因此没有类型提示,调用就是在数组的每个值上使用反射。

速度变为:

 imaging.core=> (load-file "src/imaging/core.clj")
 Reflection warning, core.clj:45:11 - call to  aset can't be resolved.
 #'imaging.core/testrgb
 imaging.core=> (testrgb)
 "Elapsed time: 107.138 msecs"
 "Elapsed time: 359.448 msecs"
 "Elapsed time: 44267.634 msecs"
 "Elapsed time: 92.022 msecs"
 nil
 imaging.core=> (load-file "src/imaging/core.clj")
 #'imaging.core/testrgb
 imaging.core=> (testrgb)
 "Elapsed time: 102.871 msecs"
 "Elapsed time: 423.294 msecs"
 "Elapsed time: 1377.818 msecs"
 "Elapsed time: 88.026 msecs"

对于速度参考,地图正在以下位置运行:

 "Elapsed time: 2903.577 msecs"

和pmap at:

 "Elapsed time: 9351.502 msecs"