Snippets
Created by
Julio Biason
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | """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)
You can clone a snippet to your computer for local editing. Learn more.