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