Optimize the Utils.stdDev function
authorIustin Pop <iustin@google.com>
Mon, 6 Jul 2009 22:20:41 +0000 (00:20 +0200)
committerIustin Pop <iustin@google.com>
Mon, 6 Jul 2009 22:22:54 +0000 (00:22 +0200)
This patch optimizes the stdDev function in two respects:
  - first, we don't do sum . map which builds an intermediate list, but
instead use a fold over the list to build incrementally the sum;
this should reduce both the time and space characteristics, as we
have fewer objects created
  - second, we move from “a ^ 2” to “a * a” as the latter has a much
simpler implementation and thus a higher performance

Since the ‘square’ function is obsoleted by the above the patch also
removes it.

Ganeti/HTools/Utils.hs

index 0bed1d7..cd55beb 100644 (file)
@@ -77,15 +77,11 @@ fst3 (a, _, _) = a
 meanValue :: Floating a => [a] -> a
 meanValue lst = sum lst / fromIntegral (length lst)
 
--- | Squaring function
-square :: (Num a) => a -> a
-square = (^ 2)
-
 -- | Standard deviation.
 stdDev :: Floating a => [a] -> a
 stdDev lst =
     let mv = meanValue lst
-        av = sum $ map (square . (\e -> e - mv)) lst
+        av = foldl' (\accu elem -> let d = elem - mv in accu + d * d) 0.0 lst
         bv = sqrt (av / fromIntegral (length lst))
     in bv