Merge branch 'master' of ssh://lausser,shinken@shinken.git.sourceforge.net/gitroot...
[shinken.git] / shinken / load.py
blob6054e2c22e2c75df4de23f09fb4ab9f7d1da8c50
1 #!/usr/bin/env python
2 #Copyright (C) 2009-2010 :
3 # Gabes Jean, naparuba@gmail.com
4 # Gerhard Lausser, Gerhard.Lausser@consol.de
5 # Gregory Starck, g.starck@gmail.com
6 # Hartmut Goebel, h.goebel@goebel-consult.de
8 #This file is part of Shinken.
10 #Shinken is free software: you can redistribute it and/or modify
11 #it under the terms of the GNU Affero General Public License as published by
12 #the Free Software Foundation, either version 3 of the License, or
13 #(at your option) any later version.
15 #Shinken is distributed in the hope that it will be useful,
16 #but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 #GNU Affero General Public License for more details.
20 #You should have received a copy of the GNU Affero General Public License
21 #along with Shinken. If not, see <http://www.gnu.org/licenses/>.
24 import time
25 import math
27 #EXP_1=1/math.exp(5/60.0)
28 #EXP_5=1/math.exp(5/(5*60.0))
29 #EXP_15=1/math.exp(5/(15*60.0))
31 #From advance load average's code (another of my projects :) )
32 #def calc_load_load(load, exp,n):
33 # load = n + exp*(load - n)
34 # return (load, exp)
37 #This class if for having a easy Load calculation
38 #without having to send value at regular interval
39 #(but it's more efficient if you do this :) ) and not
40 #having a list and all. Just an object, an update and a get
41 #You can define m : the average is for m minutes. The val is
42 #the initial value. It's better if it's 0 but you can choice.
45 class Load:
46 #m = number of minutes for the average
47 #val = initial_value
48 def __init__(self, m=1, initial_value=0):
49 self.exp = 0 #first exp
50 self.m = m #Number of minute of the avg
51 self.last_update = 0 #last update of the value
52 self.val = initial_value #first value
55 def update_load(self, new_val):
56 #The first call do not change the value, just tag
57 #the begining of last_update
58 if self.last_update == 0:
59 self.last_update = time.time()
60 return
61 now = time.time()
62 try:
63 diff = now - self.last_update
64 self.exp = 1/math.exp(diff/ (self.m*60.0))
65 self.val = new_val + self.exp*(self.val - new_val)
66 self.last_update = now
67 except OverflowError: #if the time change without notice, we overflow :(
68 pass
69 except ZeroDivisionError: #do not care
70 pass
73 def get_load(self):
74 return self.val
77 if __name__ == '__main__':
78 l = Load()
79 t = time.time()
80 for i in xrange(1, 300):
81 l.update_load(1)
82 print '[', int(time.time() - t), ']', l.get_load(), l.exp
83 time.sleep(5)