Completed
Branch master (7e8cc2)
by Kenny
03:21 queued 19s
created

Differential.per_second()   A

Complexity

Conditions 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
c 1
b 1
f 0
dl 0
loc 21
rs 9.3142
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
14
class Differential(object):
15
    """Computes the rate of change of a set of metrics."""
16
17
    def __init__(self):
18
        self.metrics = {}
19
20
    def per_second(self, name, val, ts):
21
        """Records and returns the rate of change of a metric in units/second.
22
23
        :param name: The name of a metric
24
        :type name: str
25
        :param val: The value of a metric
26
        :type val: int or float
27
        :rtype: int or float
28
        """
29
        ret = type(val)(0)
30
        if name not in self.metrics:
31
            self.metrics[name] = (val, ts)
32
        else:
33
            pval, ptime = self.metrics[name]
34
            dval = val - pval
35
            dtime = ts - ptime
36
            if dtime > 0:
37
                ret = dval / dtime
38
            else:
39
                ret = 0
40
        return ret
41