From: Tony Mack Date: Fri, 3 Apr 2009 17:57:53 +0000 (+0000) Subject: logger nad profiler X-Git-Tag: sfa-0.9-0@14641~524 X-Git-Url: http://git.onelab.eu/?a=commitdiff_plain;h=f8c9d51e43769e4e15bd4abbb365351d43d85b17;p=sfa.git logger nad profiler --- diff --git a/geni/util/debug.py b/geni/util/debug.py new file mode 100644 index 00000000..b8dac85e --- /dev/null +++ b/geni/util/debug.py @@ -0,0 +1,54 @@ +import time +import sys +import syslog + +class unbuffered: + """ + Write to /var/log/httpd/error_log. See + + http://www.modpython.org/FAQ/faqw.py?req=edit&file=faq02.003.htp + """ + + def write(self, data): + sys.stderr.write(data) + sys.stderr.flush() + +log = unbuffered() + +def profile(callable): + """ + Prints the runtime of the specified callable. Use as a decorator, e.g., + + @profile + def foo(...): + ... + + Or, equivalently, + + def foo(...): + ... + foo = profile(foo) + + Or inline: + + result = profile(foo)(...) + """ + + def wrapper(*args, **kwds): + start = time.time() + result = callable(*args, **kwds) + end = time.time() + args = map(str, args) + args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.items()] + print >> log, "%s (%s): %f s" % (callable.__name__, ", ".join(args), end - start) + return result + + return wrapper + +if __name__ == "__main__": + def sleep(seconds = 1): + time.sleep(seconds) + + sleep = profile(sleep) + + sleep(1)