[英]clojure amap is very slow
因此,我一直在clojure中進行基本的圖像處理(只是將rgb轉換為灰度),而amap存在嚴重問題; 即,我不能很快。
我已經能夠使用類型提示將其從21000ms降低到大約8000ms,但這就是它。 相比之下,法線貼圖的運行時間約為400毫秒...
我還能做些什么使它像這樣的簡單操作一樣快?
(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)
)
)
我不得不加位和代碼段運行您的樣品,所以這里所產生的要點開始。
不知何故,我覺得反思開始了,因為get需要一些有關類型的幫助以使速度達到最大。 這是一個相關的SO線程 。
使用:
(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在:
"Elapsed time: 9351.502 msecs"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.