From e6f4f05c9c4fb1ddbb3726445fad88f171dab985 Mon Sep 17 00:00:00 2001
From: Iustin Pop <iustin@google.com>
Date: Tue, 7 Jul 2009 00:20:41 +0200
Subject: [PATCH] Optimize the Utils.stdDev function
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

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 | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)

diff --git a/Ganeti/HTools/Utils.hs b/Ganeti/HTools/Utils.hs
index 0bed1d791..cd55bebf3 100644
--- a/Ganeti/HTools/Utils.hs
+++ b/Ganeti/HTools/Utils.hs
@@ -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
 
-- 
GitLab