Completed
Push — master ( 754be8...27a8ca )
by Kenny
02:01
created

Differential.per_second()   B

Complexity

Conditions 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
c 1
b 1
f 0
dl 0
loc 30
rs 8.5806
1
# -*- coding: utf-8 -*-
2
"""
3
.. moduleauthor:: Kenny Freeman <[email protected]>
4
5
"""
6
7
__author__ = 'Kenny Freeman'
8
__email__ = '[email protected]'
9
__version__ = '0.3.3'
10
__license__     = "ISCL"
11
__docformat__   = 'reStructuredText'
12
13
import platform
14
15
16
# use CNT_LIMIT to detect counters wrapping over
17
arch = platform.architecture()[0] # eg. ('64bit', 'ELF')
18
if arch == '64bit':
19
    MAX_CNT = 18446744073709551615L
20
elif arch == '32bit':
21
    MAX_CNT = 4294967295
22
else:
23
    MAX_CNT = sys.maxint
24
25
26
class Differential(object):
27
    """Computes the rate of change of a set of metrics."""
28
29
    def __init__(self):
30
        self.metrics = {}
31
32
    def per_second(self, name, val, ts):
33
        """Records and returns the rate of change of a metric in units/second.
34
35
        Assumes values will be < MAX_CNT and detects and corrects overflow.
36
37
        :param name: The name of a metric
38
        :type name: str
39
        :param val: The value of a metric
40
        :type val: int or float
41
        :param max: The maximum possible value for val
42
        :type val: int or float
43
        :rtype: int or float
44
        """
45
        ret = type(val)(0)
46
        if name not in self.metrics:
47
            self.metrics[name] = (val, ts)
48
        else:
49
            # get the previous value
50
            pval, ptime = self.metrics[name]
51
            self.metrics[name] = (val, ts)
52
            # check for counter wrap
53
            if val < pval:
54
                pval = pval - MAX_CNT
55
            dval = val - pval
56
            dtime = ts - ptime
57
            if dtime > 0:
58
                ret = float(dval) / float(dtime)
59
            else:
60
                ret = 0
61
        return ret
62