Snippets

Julio Biason Stupid APM in Python

Created by Julio Biason last modified
"""APM monitoring class."""

import sys
import time


class FuncInfo(object):
    """Function to store the execution of each function."""

    __slots__ = ['name', 'call_count', 'avg_time', 'low_time', 'high_time']

    def __init__(self, name):
        self.name = name
        self.call_count = 0
        self.avg_time = 0
        self.low_time = sys.maxint
        self.high_time = 0

    def add_call(self, exec_time):
        """Add an execution time to the function."""
        self.avg_time = ((self.avg_time * self.call_count) + exec_time) / \
            (self.call_count + 1)
        self.call_count += 1
        self.low_time = min(self.low_time, exec_time)
        self.high_time = max(self.high_time, exec_time)
        return

    def __str__(self):
        return '{record.name}: {record.call_count} calls, ' \
            '{record.avg_time:.4f}s avg exec time, ' \
            '{record.low_time:.4f}s fastest, ' \
            '{record.high_time:.4f}s slowest'.format(record=self)

    def __repr__(self):
        return str(self)        # No, but ok


# This is our data, but don't tell anyone.
__stack = []
__functions = {}


def monitor(func):
    """Add a APM monitoring over a function."""

    func_name = func.__name__

    def wrapped(*args, **kwargs):
        stacked_func_name = "|".join([stack.name for stack in __stack] +
                                     [func_name])

        if stacked_func_name not in __functions:
            __functions[stacked_func_name] = FuncInfo(func_name)
        __stack.append(__functions[stacked_func_name])

        start = time.time()
        result = func(*args, **kwargs)
        exec_time = time.time() - start

        __functions[stacked_func_name].add_call(exec_time)
        __stack.pop()
        return result

    wrapped.__name__ == func.__name__
    wrapped.__doc__ == func.__doc__
    wrapped.__dict__.update(func.__dict__)
    return wrapped


def execution():
    return __functions
    
    
################## SAMPLE EXECUTION

"""Main function."""

from __future__ import print_function

import time
import pprint

import apm


@apm.monitor
def subfunction():
    print("I do nothing")


@apm.monitor
def testing():
    time.sleep(1)
    subfunction()
    return 43


if __name__ == "__main__":
    print("Result: " + str(testing()))
    testing()       # ignore results
    testing()       # again
    subfunction()   # just because
    pprint.pprint(apm.execution())

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.