From f8c9d51e43769e4e15bd4abbb365351d43d85b17 Mon Sep 17 00:00:00 2001 From: Tony Mack Date: Fri, 3 Apr 2009 17:57:53 +0000 Subject: [PATCH] logger nad profiler --- geni/util/debug.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 geni/util/debug.py 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) -- 2.47.0