【发布时间】:2014-01-14 04:15:16
【问题描述】:
我需要在调色板ps 中找到与给定颜色p 最接近的颜色。如何在不更改类型的情况下尽快使函数nearestColor
Pixel8 或 PixelRGB8。到目前为止,我已经尝试过内联。
import qualified Data.Vector as V
type Pixel8 = Word8
data PixelRGB8 = PixelRGB8 {-# UNPACK #-} !Pixel8 -- Red
{-# UNPACK #-} !Pixel8 -- Green
{-# UNPACK #-} !Pixel8 -- Blue
deriving (Eq, Ord, Show)
nearestColor :: PixelRGB8 -> Vector PixelRGB8 -> PixelRGB8
nearestColor p ps = snd $ V.minimumBy comp ds
where
ds = V.map (\px -> (dist2Px px p, px)) ps
comp a b = fst a `compare` fst b
dist2Px :: PixelRGB8 -> PixelRGB8 -> Int
dist2Px (PixelRGB8 r1 g1 b1) (PixelRGB8 r2 g2 b2) = dr*dr + dg*dg + db*db
where
(dr, dg, db) =
( fromIntegral r1 - fromIntegral r2
, fromIntegral g1 - fromIntegral g2
, fromIntegral b1 - fromIntegral b2 )
【问题讨论】:
-
我们能看到
dist2Px的代码吗? -
到目前为止您尝试过什么?你可以尝试分析它,你可以内联那些本地函数
ds和comp,你可以编译到核心并搜索瓶颈,然后编译到汇编并确保你有紧密的循环。 -
我怀疑构建一个只有距离的向量,并使用
minIndex在原始向量中查找结果可能会更快:ps ! V.minIndex (V.map (\px -> dist2Px px p) ps) -
@Tamil - 不会加快速度,但它更干净,谢谢。
-
您究竟想优化什么:单个函数调用的时间,还是针对不同颜色但相同调色板的大量调用的平均时间?
标签: haskell optimization